Skip to content

CommandBuffer

Martin Evans edited this page Aug 6, 2024 · 2 revisions

The only way to make structural changes to the world (creating or destroying entities, adding or removing components) is through a CommandBuffer. A CommandBuffer allows you to queue multiple commands, the world is only modified when the buffered is executed.

var buffer = new CommandBuffer(world);

// Create an entity. This returns a "buffered entity" object that can be used to resolve the real Entity when it is eventually created
var bufferedEntity = setup.Create()
     .Set(new Position(new Vector3(1, 2, 3)))
     .Set(new Velocity(new Vector3(0, 1, 0)))
     .Set(new Mass(1));

// Execute the buffer, receive a "resolver"
using var resolver = buffer.Playback();

// Resolve the buffered entity into a real Entity
var entity = bufferedEntity.Resolve(resolver);

Create An Entity

To create a new Entity simply call buffer.Create(), this returns BufferedEntity. The BufferedEntity can have components set on it using entity.Set(new Component()). By default the buffer will throw an exception if the same component is attached twice (doing so is usually an error), but you can allow duplicates by passing overwrite:true to the Set call.

When the buffer is executed it returns a Resolver which can be used to resolve the Entity which was created from a given BufferedEntity.

Delete An Entity

An existing Entity can be destroyed by calling buffer.Destroy(entity). This has some special behaviours:

  • If the Entity has any Phantom components the entity will become a phantom instead of being destroyed.
  • If the Entity is a phantom it will be destroyed.
  • If the Entity has any disposable components their disposal behaviour will be executed when the buffer is executed.

Adding/Modifying A Component

A component can be attached to an existing Entity by calling buffer.Set(entity, new Component()). If the Entity already has that component attached it will simply be overwritten when the buffer is executed.

Removing A Component

A component can be removed from an existing Entity by calling buffer.Remove<TComponent>(entity). This has some special behaviours:

Ordering

If "conflicting" commands are added to the CommandBuffer, it will act as if they were applied "in order". For example double sets:

  1. Set component A(1)
  2. Set component A(2)

The final result will be A(2) attached to the Entity.

Conflicting set and remove:

  1. Set component A(1)
  2. Remove component A

Here, nothing will be added to the entity.

Clone this wiki locally