Add set_parent and remove_parent to EntityCommands (#6189)

I found myself doing
```rust
let child = commands.spawn(..).id();
commands.entity(parent).add_child(child);
```
When that could just be
```rust
commands.spawn(..).set_parent(parent);
```

Adding `set_parent` was trivial as it's just an `AddChild` command. Most of the changes are for `remove_parent`.
Also updated some outdated docs.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
This commit is contained in:
ira 2022-10-24 14:33:49 +00:00
parent f7d3fbc7d5
commit c9ec5c771a

View File

@ -155,7 +155,7 @@ impl Command for InsertChildren {
}
}
/// Command that pushes children to the end of the entity's children
/// Command that pushes children to the end of the entity's [`Children`].
#[derive(Debug)]
pub struct PushChildren {
parent: Entity,
@ -175,7 +175,7 @@ impl Command for PushChildren {
}
}
/// Command that removes children from an entity, and removes that child's parent and inserts it into the previous parent component
/// Command that removes children from an entity, and removes that child's parent.
pub struct RemoveChildren {
parent: Entity,
children: SmallVec<[Entity; 8]>,
@ -187,6 +187,27 @@ impl Command for RemoveChildren {
}
}
/// Command that removes the parent of an entity, and removes that entity from the parent's [`Children`].
pub struct RemoveParent {
child: Entity,
}
impl Command for RemoveParent {
fn write(self, world: &mut World) {
if let Some(parent) = world.get::<Parent>(self.child) {
let parent_entity = parent.get();
remove_from_children(world, parent_entity, self.child);
world.entity_mut(self.child).remove::<Parent>();
if let Some(mut events) = world.get_resource_mut::<Events<_>>() {
events.send(HierarchyEvent::ChildRemoved {
child: self.child,
parent: parent_entity,
});
}
}
}
}
/// Struct for building children onto an entity
pub struct ChildBuilder<'w, 's, 'a> {
commands: &'a mut Commands<'w, 's>,
@ -288,6 +309,10 @@ pub trait BuildChildren {
/// will have those children removed from its list. Removing all children from a parent causes its
/// [`Children`] component to be removed from the entity.
fn add_child(&mut self, child: Entity) -> &mut Self;
/// Sets the parent of this entity.
fn set_parent(&mut self, parent: Entity) -> &mut Self;
/// Removes the parent of this entity.
fn remove_parent(&mut self) -> &mut Self;
}
impl<'w, 's, 'a> BuildChildren for EntityCommands<'w, 's, 'a> {
@ -346,6 +371,18 @@ impl<'w, 's, 'a> BuildChildren for EntityCommands<'w, 's, 'a> {
self.commands().add(AddChild { child, parent });
self
}
fn set_parent(&mut self, parent: Entity) -> &mut Self {
let child = self.id();
self.commands().add(AddChild { child, parent });
self
}
fn remove_parent(&mut self) -> &mut Self {
let child = self.id();
self.commands().add(RemoveParent { child });
self
}
}
/// Struct for adding children to an entity directly through the [`World`] for use in exclusive systems