Remove Children component when calling despawn_descendants (#8476)

# Objective

Fix #8474
This commit is contained in:
ira 2023-04-24 16:14:52 +02:00 committed by GitHub
parent a4323d5641
commit 5dec3236ac
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -46,9 +46,9 @@ fn despawn_with_children_recursive_inner(world: &mut World, entity: Entity) {
}
}
fn despawn_children(world: &mut World, entity: Entity) {
if let Some(mut children) = world.get_mut::<Children>(entity) {
for e in std::mem::take(&mut children.0) {
fn despawn_children_recursive(world: &mut World, entity: Entity) {
if let Some(children) = world.entity_mut(entity).take::<Children>() {
for e in children.0 {
despawn_with_children_recursive_inner(world, e);
}
}
@ -76,7 +76,7 @@ impl Command for DespawnChildrenRecursive {
entity = bevy_utils::tracing::field::debug(self.entity)
)
.entered();
despawn_children(world, self.entity);
despawn_children_recursive(world, self.entity);
}
}
@ -127,11 +127,9 @@ impl<'w> DespawnRecursiveExt for EntityMut<'w> {
)
.entered();
// SAFETY: The location is updated.
unsafe {
despawn_children(self.world_mut(), entity);
self.update_location();
}
self.world_scope(|world| {
despawn_children_recursive(world, entity);
});
}
}
@ -226,4 +224,26 @@ mod tests {
]
);
}
#[test]
fn despawn_descendants() {
let mut world = World::default();
let mut queue = CommandQueue::default();
let mut commands = Commands::new(&mut queue, &world);
let parent = commands.spawn_empty().id();
let child = commands.spawn_empty().id();
commands
.entity(parent)
.add_child(child)
.despawn_descendants();
queue.apply(&mut world);
// The parent's Children component should be removed.
assert!(world.entity(parent).get::<Children>().is_none());
// The child should be despawned.
assert!(world.get_entity(child).is_none());
}
}