Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Add despawn_children #2903

Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions crates/bevy_transform/src/hierarchy/hierarchy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ pub struct DespawnRecursive {
entity: Entity,
}

#[derive(Debug)]
pub struct DespawnChildrenRecursive {
entity: Entity,
}

pub fn despawn_with_children_recursive(world: &mut World, entity: Entity) {
// first, make the entity's own parent forget about it
if let Some(parent) = world.get::<Parent>(entity).map(|parent| parent.0) {
Expand All @@ -36,15 +41,32 @@ fn despawn_with_children_recursive_inner(world: &mut World, entity: Entity) {
}
}

fn despawn_children_recursive(world: &mut World, entity: Entity) {
if let Some(mut children) = world.get_mut::<Children>(entity) {
for e in std::mem::take(&mut children.0) {
despawn_with_children_recursive_inner(world, e);
}
}
}

impl Command for DespawnRecursive {
fn write(self, world: &mut World) {
despawn_with_children_recursive(world, self.entity);
}
}

impl Command for DespawnChildrenRecursive {
fn write(self, world: &mut World) {
despawn_children_recursive(world, self.entity);
}
}

pub trait DespawnRecursiveExt {
/// Despawns the provided entity and its children.
fn despawn_recursive(self);

/// Despawns the provided entity's children.
fn despawn_children_recursive(&mut self);
}

impl<'w, 's, 'a> DespawnRecursiveExt for EntityCommands<'w, 's, 'a> {
Expand All @@ -53,6 +75,11 @@ impl<'w, 's, 'a> DespawnRecursiveExt for EntityCommands<'w, 's, 'a> {
let entity = self.id();
self.commands().add(DespawnRecursive { entity });
}

fn despawn_children_recursive(&mut self) {
let entity = self.id();
self.commands().add(DespawnChildrenRecursive { entity });
}
}

impl<'w> DespawnRecursiveExt for EntityMut<'w> {
Expand All @@ -65,6 +92,15 @@ impl<'w> DespawnRecursiveExt for EntityMut<'w> {
despawn_with_children_recursive(self.world_mut(), entity);
}
}

fn despawn_children_recursive(&mut self) {
let entity = self.id();
// SAFE: The location is updated.
unsafe {
despawn_children_recursive(self.world_mut(), entity);
self.update_location();
}
}
}

#[cfg(test)]
Expand Down