Skip to content

CommandBuffer ​

Records structural changes and applies them later, in order. Use it inside filter loops and nested loops where changing other entities is unsafe.

csharp
partial class CollisionSystem : IInitSystem, IRunSystem {
    readonly CommandBuffer _buffer = new CommandBuffer();   // one per system; zero allocations after warmup
    Filter _projectiles;
    Filter _targets;

    public void Init(World world, SharedData shared) {
        _projectiles = world.Filter().Inc<Projectile>().End();
        _targets = world.Filter().Inc<Target>().End();
    }

    public void Run(World world) {
        foreach (int e in _projectiles) {
            foreach (int t in _targets) {
                if (Hits(e, t)) {
                    _buffer.DestroyEntity(world.GetEntity(e));
                    // An event, not a buffered component: every projectile that hits this
                    // target in the frame adds its own Hit (Set would keep only the last one)
                    world.AddEvent(world.GetEntity(t), new Hit { Damage = 10 });
                    break;   // a projectile hits one target and is destroyed once
                }
            }
        }
        _buffer.Playback(world);
    }
}

Keep one buffer per system: payloads are stored per component type without boxing, and after warmup the buffer allocates nothing.

The hit is not a command in the buffer. Two projectiles may hit one target in the same frame, and a component holds one value per entity: recorded with Add, the second hit throws at playback; recorded with Set, it overwrites the first and the target takes 10 damage, not 20. world.AddEvent appends every hit to the target's EventBuffer<Hit> at once, which is safe inside the loops: it changes the membership of neither filter. Register OneFrame<EventBuffer<Hit>>() on the runner so the hits are removed at the end of the frame.

Commands ​

CommandAt playback
CreateEntity<T>(T)Creates an entity with that component. Returns a PendingEntity usable as a target for later commands in the same buffer.
Add<T>(entity, T)Throws if the component exists, like World.Add.
Set<T>(entity, T)Adds or overwrites. An overwrite is a plain write that change tracking counts as a change; AutoReset does not run on the old value, so writing back a modified copy that shares the old value's references keeps them. Typed listeners see OnAdded only when the component was missing. An EventBuffer<T> written over one that holds a list returns that list to the pool, also when the new buffer has no list (default clears the entity's events), so copies of the old buffer no longer see it. Not for adding events, see below.
Remove<T>(entity)No-op if the component is absent.
DestroyEntity(entity)No-op if the entity is already dead.

Every command except CreateEntity accepts either an Entity or a PendingEntity. A PendingEntity is valid only in the buffer that returned it, until that buffer's next Playback or Clear: it names the entity by its position among the buffer's CreateEntity commands, so after Playback the same handle names the first entity of the next recording. Under KENSEI_DEBUG recording a command on a PendingEntity of another buffer, of an earlier recording or a default one throws InvalidOperationException (that command is not recorded, and the commands recorded before it stay in the buffer); release does not check it (up to 2.4.0 no build did). That includes a pattern that happened to work up to 2.4.0: a command recorded on a PendingEntity after its Playback, before the buffer recorded another CreateEntity, reached the entity that Playback had created. Under KENSEI_DEBUG it throws now; in release it still lands there, and on another entity as soon as the new recording creates one first. To reach an entity after Playback, keep the Entity it created (for example from a listener) instead.

PendingEntity is an unmanaged struct in both builds (it holds an id, under KENSEI_DEBUG also the numbers of its buffer and recording, never a reference), so a batch of handles can live in a stackalloc span; its size differs between the builds (4 and 12 bytes).

csharp
PendingEntity blast = buffer.CreateEntity(new Explosion { Radius = 3f });
buffer.Add(blast, new DamageEvent { Value = 25 });   // targets the entity created above
buffer.DestroyEntity(projectile);                   // skipped if already dead at playback

buffer.Playback(world);                             // applies in order, then clears the buffer
  • Commands whose Entity is dead at playback are skipped, so "destroy if still alive" needs no check.
  • If a command throws, the rest of the buffer is discarded.
  • Commands that a listener records into the same buffer during Playback are applied by that Playback, after the ones recorded before, for any number of pending entities they create (up to 2.4.0 more than the buffer had room for, 16 at first, threw IndexOutOfRangeException).
  • Playback clears the buffer; Clear() discards recorded commands without applying them, and Count returns the number of recorded commands.

Events and Set

Do not record events as var b = world.Get<EventBuffer<Hit>>(e); b.Add(h); cb.Set(e, b); (2.1.1 suggested it). The copy shares the entity's list, so the event is added at once, not at playback; and if the buffer is removed before Playback — a OneFrame cleanup of a nested runner, a DelHere, a Remove recorded earlier in the same buffer — the copy is stale and its events are gone. Set then stores an empty buffer, or keeps the entity's current one, rather than a list that went back to the pool (which 2.2.1 and earlier did, handing one list to two entities). Call world.AddEvent(e, h) directly; to defer it, keep the (Entity, Hit) pairs yourself and call AddEvent after Playback. See copies of a buffer.