Relationships and hierarchy
Build parent and child hierarchies with ChildOf and Children, spawn children inline, walk the tree, and define your own relationships between entities.
On this page
Entities often belong together: a character and the sword in its hand, a UI panel and its buttons, a car and its wheels. A relationship links entities with components. The built-in one is the parent and child hierarchy, made of ChildOf (on the child) and Children (on the parent). Transforms and visibility follow it: a child moves, rotates and hides with its parent.
Parents and children#
ChildOf(parent) on an entity makes it a child of parent. The engine keeps the parent's Children list up to date for you.
use neo::prelude::*;
fn setup(mut commands: Commands) {
let car = commands.spawn((Name::new("Car"), Transform::default())).id();
commands.spawn((Name::new("Wheel"), Transform::from_xyz(1.0, 0.0, 1.0), ChildOf(car)));
}The usual ways to build a hierarchy:
fn spawn_car(mut commands: Commands) {
// children! inside the parent's bundle
commands.spawn((
Name::new("Car"),
Transform::default(),
children![
(Name::new("Wheel FL"), Transform::from_xyz(-1.0, 0.0, 1.0)),
(Name::new("Wheel FR"), Transform::from_xyz(1.0, 0.0, 1.0)),
],
));
// with_children, for loops and logic
commands
.spawn((Name::new("Truck"), Transform::default()))
.with_children(|parent| {
for x in [-1.0, 1.0] {
parent.spawn((Name::new("Wheel"), Transform::from_xyz(x, 0.0, 2.0)));
}
});
// with_child, for one child
commands
.spawn((Name::new("Bike"), Transform::default()))
.with_child((Name::new("Rider"), Transform::from_xyz(0.0, 1.0, 0.0)));
}| Method or type | What it does |
|---|---|
children![a, b, ..] | Spawns each bundle as a child, as part of the parent's bundle. |
Children::spawn((Spawn(a), SpawnIter(iter), SpawnWith(f))) | The same, mixing single bundles, iterators and closures. |
with_children(f), with_child(bundle) | Spawn children from EntityCommands. |
add_child(id), add_children(&[ids]), insert_children(index, &[ids]) | Adopt existing entities. |
remove::<ChildOf>() on the child, detach_child(id), detach_all_children() | Detach without despawning. |
despawn_children() | Despawn the children, keep the parent. |
despawn() | Despawn the entity and everything below it. |
An entity has at most one parent. Inserting a new ChildOf moves it to the new parent.
Reading the hierarchy#
fn list_wheels(cars: Query<(&Name, &Children)>, names: Query<&Name>) {
for (car, children) in &cars {
for child in children {
if let Ok(name) = names.get(*child) {
info!("{car} has {name}");
}
}
}
}
fn parent_of(wheels: Query<&ChildOf>) {
for child_of in &wheels {
let parent: Entity = child_of.parent();
// ...
}
}Queries can walk the tree for you:
Method on a Query | Yields |
|---|---|
iter_ancestors(entity) | Parent, grandparent, up to the root. Use it on a Query<&ChildOf>. |
root_ancestor(entity) | The top of the tree. Use it on a Query<&ChildOf>. |
iter_descendants(entity) | Every entity below it. Use it on a Query<&Children>. |
iter_descendants_depth_first(entity) | The same, in depth-first order. |
iter_leaves(entity) | Descendants with no children. Use it on a Query<&Children>. |
iter_siblings(entity) | The other children of the same parent. Use it on a Query<(Option<&ChildOf>, Option<&Children>)>. |
fn whole_tree(children: Query<&Children>, root: Single<Entity, With<Car>>) {
for entity in children.iter_descendants(*root) {
info!("{entity}");
}
}
#[derive(Component)]
struct Car;What the hierarchy affects#
- Transforms. A child's
Transformis relative to its parent. The engine computes each entity's world-spaceGlobalTransforminPostUpdate. See Transforms. - Visibility. A hidden parent hides its children.
- Despawning. Despawning a parent despawns its children.
- Events. Entity events marked
propagatebubble from child to parent. See Events and observers. - UI. A UI node's children are laid out inside it.
Your own relationships#
You can define any one-to-many relationship the same way. One component, on the source, holds the target; the other, on the target, lists the sources and is maintained for you.
/// The unit this unit is attacking.
#[derive(Component)]
#[relationship(relationship_target = TargetedBy)]
struct Targeting(Entity);
/// Every unit attacking this one. Kept up to date automatically; don't edit it.
#[derive(Component)]
#[relationship_target(relationship = Targeting)]
struct TargetedBy(Vec<Entity>);
fn setup(mut commands: Commands) {
let boss = commands.spawn(Name::new("Boss")).id();
commands.spawn((Name::new("Knight"), Targeting(boss)));
commands
.entity(boss)
.with_related::<Targeting>(Name::new("Archer")) // spawns an Archer targeting the boss
.with_related_entities::<Targeting>(|spawner| {
spawner.spawn(Name::new("Mage"));
});
}- Relationship components are immutable. To retarget, insert a new
Targeting; to end the relationship, remove it. - Add
linked_spawnto the target side (#[relationship_target(relationship = Targeting, linked_spawn)]) to despawn the sources when the target is despawned, asChildrendoes. related!(TargetedBy[a, b])spawns sources inline, likechildren!.- The traversal methods above (
iter_ancestorsand so on) work for any relationship.
Examples#
Run these from the engine core's workspace:
| Example | What it shows |
|---|---|
cargo run --example hierarchy | Every way to spawn children, rotating a parent and its children, and despawning. |
cargo run --example relationships | A custom Targeting relationship, cycle detection and retargeting. |