From a8c2e51d7d0088b57483320d2dd835a4f14fc5ba Mon Sep 17 00:00:00 2001 From: ira Date: Mon, 10 Oct 2022 23:40:32 +0000 Subject: [PATCH] Fix `RemoveChildren` command (#6192) # Objective `RemoveChildren` could remove the `Parent` component from children belonging to a different parent, which breaks the hierarchy. This change looks a little funny because I'm reusing the events to avoid needing to clone the parent's `Children`. Co-authored-by: devil-ira --- crates/bevy_hierarchy/src/child_builder.rs | 24 +++++++++++++--------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/crates/bevy_hierarchy/src/child_builder.rs b/crates/bevy_hierarchy/src/child_builder.rs index e759121daa63d..67f16c555112c 100644 --- a/crates/bevy_hierarchy/src/child_builder.rs +++ b/crates/bevy_hierarchy/src/child_builder.rs @@ -1,7 +1,4 @@ -use crate::{ - prelude::{Children, Parent}, - HierarchyEvent, -}; +use crate::{Children, HierarchyEvent, Parent}; use bevy_ecs::{ bundle::Bundle, entity::Entity, @@ -68,12 +65,19 @@ fn update_old_parents(world: &mut World, parent: Entity, children: &[Entity]) { fn remove_children(parent: Entity, children: &[Entity], world: &mut World) { let mut events: SmallVec<[HierarchyEvent; 8]> = SmallVec::new(); - for child in children { - world.entity_mut(*child).remove::(); - events.push(HierarchyEvent::ChildRemoved { - child: *child, - parent, - }); + if let Some(parent_children) = world.get::(parent) { + for &child in children { + if parent_children.contains(&child) { + events.push(HierarchyEvent::ChildRemoved { child, parent }); + } + } + } else { + return; + } + for event in &events { + if let &HierarchyEvent::ChildRemoved { child, .. } = event { + world.entity_mut(child).remove::(); + } } push_events(world, events);