EasyEcs

Hierarchy

Link entities to a parent with ChildOf, list children with Children, walk a subtree with Descendants, destroy a parent with its subtree.

A ship carries turrets, a turret carries a gun, a squad leader leads its members. ChildOf(parent) links an entity to its parent: world.Children(parent) lists the children, and destroying the parent destroys its descendants, so a ship that sinks takes its turrets with it without a line of cleanup code. ChildOf is an indexed EntityId link like any other, with the destroy cascade switched on.

When to use it

Use it for

Entities that live and die with another one: turrets on a ship, items a player carries, members of a squad, the parts of a vehicle. Moving a player and everything it owns to another world or server.

Skip it for

Links that must not kill the linked entity (a target, a follower): use your own EntityId key with Keep or Remove. An entity with several "parents" (a member of many parties): use a relation. Transform propagation is not built in: the sample below is a system you write.

How to use it

Attach children

Give the child a ChildOf with the parent's id (a handle converts to it).

public record struct Name(string Value) : IComponent;
var ship = world.CreateEntity(new Name("ship"));
var turret = world.CreateEntity(new Name("turret"), new ChildOf(ship));
var gun = world.CreateEntity(new Name("gun"), new ChildOf(turret));

List them

world.Children(parent) returns the entities whose ChildOf points at the parent: O(1), then O(1) per child. The first call indexes every ChildOf once.

foreach (var child in world.Children(ship)) { /* the turret */ }

Walk a subtree: Descendants

world.Descendants(root) walks the whole subtree below the root, depth first, each entity before its own children; the root itself is not one of them. It costs O(1) per entity and allocates nothing once warm. Use it where a whole tree is the unit (saving, moving or counting it); propagation that needs each parent's result goes through Children level by level.

int parts = 0;
foreach (var part in world.Descendants(ship)) parts++;   // the turret, then its gun
  • Destroying during the walk is allowed: an entity destroyed before the walk reaches it is skipped.
  • A walk inside a walk works: the inner one allocates a stack of its own (the outer one holds the world's).
  • A ChildOf cycle (an entity that is its own ancestor) throws InvalidOperationException when the walk reaches it.
  • Changing ChildOf during the walk (re-parenting, detaching) is not allowed: it rewrites the child lists the walk is reading. Collect first, then change.

Re-parent and detach

ChildOf is a value like any other: set a new one to re-parent, remove it to make the entity a root.

gun.Set(new ChildOf(ship));                // the gun now hangs on the ship
turret.Remove<ChildOf>();                  // the turret is a root

Destroy a parent

Destroying a parent destroys its children, and theirs, in the same call.

ship.Destroy();                            // the gun goes with it; the detached turret stays
bool gunAlive = gun.IsAlive;               // false

Changing what a destroy does

ChildOf starts with TargetPolicy.Destroy. Like any target policy it can be changed per world: Remove makes the children of a destroyed parent roots, Keep leaves their ChildOf pointing at the dead id.

world.Index<ChildOf, EntityId>().WhenTargetDestroyed(TargetPolicy.Remove);   // orphans become roots
  • A child that holds a cleanup component is retired, not freed: it keeps its cleanup components with the Destroyed tag, and its own children go with it.
  • A cycle (an entity that is its own ancestor) ends: destroying any of them destroys the loop.
  • ChildOf cannot be disabled (Disable<ChildOf>() throws): a parent's destroy must find its children.

Transform propagation

EasyEcs has no transform component. Propagation is a system: start at the roots (Without<ChildOf>) and walk down with Children, so each world position is computed from its parent's new one.

public record struct LocalPosition(float X, float Y) : IComponent;
public record struct WorldPosition(float X, float Y) : IComponent;
PropagateTransforms.cs
public class PropagateTransforms : EcsSystem
{
    // Roots: their world position is their local one; then each subtree follows its parent.
    [ForEach, Without<ChildOf>]
    static void FromRoot(Entity root, in LocalPosition local, ref WorldPosition position)
    {
        position = new WorldPosition(local.X, local.Y);
        Follow(root, position);
    }

    static void Follow(Entity parent, WorldPosition at)
    {
        foreach (var child in parent.World.Children(parent)) 
        {
            ref readonly var local = ref child.LocalPosition;
            var position = new WorldPosition(at.X + local.X, at.Y + local.Y);
            child.WorldPosition = position;
            Follow(child, position);
        }
    }
}
world.AddSystem<PropagateTransforms>();
var hull = world.CreateEntity(new LocalPosition(10, 0), new WorldPosition());
var mount = world.CreateEntity(new LocalPosition(0, 2), new WorldPosition(), new ChildOf(hull));
var barrel = world.CreateEntity(new LocalPosition(1, 0), new WorldPosition(), new ChildOf(mount));
world.Update();                            // barrel: WorldPosition(11, 2)

The method takes an Entity, so the system runs alone (it reads and writes other entities' components). Children are in other tables than the roots (they have ChildOf), so writing them never moves the row the pass stands on. Nothing here allocates.

Moving a hierarchy

MoveEntities and SaveEntities take the entities you list, not their children. Collect a hierarchy with Descendants and move it together: a child whose parent stays behind arrives without its ChildOf (a root there), and MoveEntities destroys the originals with their children, so a child you did not list is lost. MoveEntities takes a ReadOnlySpan<EntityId>: pass the list's span (CollectionsMarshal.AsSpan) rather than a copy of it. See migration.

using System.Runtime.InteropServices;

var player = world.CreateEntity(new Name("bob"));
world.CreateEntity(new Name("sword"), new ChildOf(player));

var group = new List<EntityId> { player.Id };
foreach (var part in world.Descendants(player)) group.Add(part.Id);   // children, grandchildren, ...
using var other = new World();
world.MoveEntities(other, CollectionsMarshal.AsSpan(group));   // bob and his sword, still linked

Full example

A ship with a turret and a gun: world positions follow the parents, the ship's subtree is listed, then the gun is re-parented, the turret detached, and the ship destroyed with what still hangs on it. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

gun at WorldPosition { X = 11, Y = 2 }
ship > turret
ship's subtree: turret gun
ship: 1 child, turret: 0 children
turret alive: True, gun alive: False
1 entity left

The gun's world position adds its parents' offsets: 10 + 0 + 1 and 0 + 2 + 0. Children lists only the turret; Descendants reaches the gun below it. After the turret is detached it survives the ship; the gun, re-parented to the ship, does not.

How to use it fast

  • Destroy the root. One Destroy follows the whole subtree inside the structural gate, with no recursion (a stack of targets). Destroying children one by one before their parent does the same work in more calls.
  • Keep depth shallow when you propagate. The walk above costs one Children lookup per entity; flat hierarchies (a ship and its turrets) walk fastest.
  • DestroyEntities<T>() destroys a whole table at once and still applies the cascade.

1,000 squads (a leader and 10 members) created, then the leaders destroyed: with members as ChildOf their leader (Cascade), and with a link of your own under TargetPolicy.Remove (RemoveLinks, HierarchyBenchmark):

CaseMeanvs baselineAllocated
Cascade590 μs1.00×0 B
RemoveLinks516 μs0.88×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

What it costs

  • Nothing until the first ChildOf. A world without a table holding ChildOf does not look for children when it destroys an entity.
  • Memory: the ChildOf column (8 bytes per row) and the index of an EntityId key (one node per child).
  • Children: O(1), then O(1) per child; the first call indexes every ChildOf.
  • Descendants: O(1) per entity of the subtree, on a stack the world keeps (0 B once warm).
  • A cascade: O(1) per destroyed entity, plus O(1) per child it had.

Pitfalls

MistakeWhat happensCaught by
Writing ChildOf through a refThe index keeps the old parentEECS015
A parent pointer of your own as an Entity fieldA managed column, not saved, no cascadeEECS017
Moving a parent without its childrenThe children stay and die with the destroyed originalCollect the group with Descendants
Collecting a tree with Children aloneGrandchildren are left outDescendants walks every level
A ChildOf cycle walked with DescendantsInvalidOperationException when the walk reaches itAt run time
Re-parenting or detaching inside a Descendants loopThe walk reads child lists that are being rewrittenCode review: collect first, then change
Disable<ChildOf>()InvalidOperationExceptionAt run time
Expecting world positions without a systemThere is no built-in transformWrite the propagation system

Compared with other libraries

Friflo has a built-in hierarchy (AddChild), but deleting a parent detaches its children, so they are deleted first; Arch and DefaultEcs have none. The same squads, created and destroyed with their members:

1,000 squads of 11: create, then destroy the leaders with their members

  • EasyEcs
  • Other libraries
EasyEcs: ChildOf0 B allocated452 μsFriflo.Engine.ECS: AddChild2.35× · 0 B allocated1.06 ms0.00 ns200 μs400 μs600 μs800 μs1.00 msTime (shorter is faster)

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Data table
LibraryCaseMeanvs EasyEcsAllocated
EasyEcsChildOf452 μs1.00×0 B
Friflo.Engine.ECSAddChild1.06 ms2.35×0 B
Edit on GitHub

Last updated on

How is this guide?

On this page