Add a method to clear all related entity to EntityCommands and friends (#18907)

# Objective

We have methods to:
- Add related entities
- Replace related entities
- Remove specific related entities

We don't have a method the remove all related entities so.

## Solution

Add a method to remove all related entities.

## Testing

A new test case.
This commit is contained in:
Brezak 2025-04-30 22:59:29 +02:00 committed by GitHub
parent b40845d296
commit 3631a64a3d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 39 additions and 0 deletions

View File

@ -281,6 +281,12 @@ impl<'w> EntityWorldMut<'w> {
self.add_related::<ChildOf>(children)
}
/// Removes all the children from this entity.
/// See also [`clear_related`](Self::clear_related)
pub fn clear_children(&mut self) -> &mut Self {
self.clear_related::<ChildOf>()
}
/// Insert children at specific index.
/// See also [`insert_related`](Self::insert_related).
pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
@ -369,6 +375,12 @@ impl<'a> EntityCommands<'a> {
self.add_related::<ChildOf>(children)
}
/// Removes all the children from this entity.
/// See also [`clear_related`](Self::clear_related)
pub fn clear_children(&mut self) -> &mut Self {
self.clear_related::<ChildOf>()
}
/// Insert children at specific index.
/// See also [`insert_related`](Self::insert_related).
pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {

View File

@ -47,6 +47,11 @@ impl<'w> EntityWorldMut<'w> {
self
}
/// Removes the relation `R` between this entity and all its related entities.
pub fn clear_related<R: Relationship>(&mut self) -> &mut Self {
self.remove::<R::RelationshipTarget>()
}
/// Relates the given entities to this entity with the relation `R`, starting at this particular index.
///
/// If the `related` has duplicates, a related entity will take the index of its last occurrence in `related`.
@ -376,6 +381,13 @@ impl<'a> EntityCommands<'a> {
})
}
/// Removes the relation `R` between this entity and all its related entities.
pub fn clear_related<R: Relationship>(&mut self) -> &mut Self {
self.queue(|mut entity: EntityWorldMut| {
entity.clear_related::<R>();
})
}
/// Relates the given entities to this entity with the relation `R`, starting at this particular index.
///
/// If the `related` has duplicates, a related entity will take the index of its last occurrence in `related`.
@ -613,4 +625,19 @@ mod tests {
assert!(!world.entity(entity).contains::<TestComponent>());
}
}
#[test]
fn remove_all_related() {
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world.spawn(ChildOf(a)).id();
let c = world.spawn(ChildOf(a)).id();
world.entity_mut(a).clear_related::<ChildOf>();
assert_eq!(world.entity(a).get::<Children>(), None);
assert_eq!(world.entity(b).get::<ChildOf>(), None);
assert_eq!(world.entity(c).get::<ChildOf>(), None);
}
}