EasyEcs

Cheat sheet

The everyday EasyEcs API on one page: entities, generated members, queries, [ForEach] parameters, attributes, singletons, indexes, prefabs, saves, options.

The whole everyday API of EasyEcs on one page, as tables and short code. Each section links to the guide page that explains it. Everything is in one namespace: using EasyEcs;.

The examples on this page share these declarations:

public record struct Position(float X, float Y) : IComponent;
public record struct Velocity(float X, float Y) : IComponent;
public record struct Health(int Value) : IComponent, ITrackChanges;          // tracked: writes are recorded
public record struct Team(int Id) : IComponent, IIndexed<int> { public int Key => Id; }
public record struct Zone(int Id) : IComponent, IGroup { public int Group => Id; }
public record struct OwnedBy(EntityId Owner) : IComponent, IIndexed<EntityId> { public EntityId Key => Owner; }
public record struct MemberOf(EntityId Target) : IRelation;                   // many links per entity
public record struct Loot(int Item);                                          // a DynamicBuffer element
public record struct Seat(int Number) : ICleanupComponent;                    // released after destroy
public struct Dead : IComponent;                                              // a tag
public record struct Clock(long Tick) : ISingletonComponent;                  // one per world

Declare data

DeclareMeansGuide
struct X : IComponentPer-entity data, one column per typeEntities and components
struct X : IComponent with no fieldsA tag: a yes-or-no state used in filtersEntities and components
struct X : ISingletonComponentOne value per worldSingletons
: ITrackChangesRows record the tick of their last write and removalChange tracking
: IIndexed<TKey> with KeyFound by value through world.Index<T, TKey>()Indexes and relations
: IIndexed<EntityId>A link to one entity, found from the targetIndexes and relations
: IRelation with TargetMany links per entity, kept in a bufferIndexes and relations
: IGroup with GroupSplits tables by value after world.GroupBy<T>()Groups
: ICleanupComponentOutlives Destroy: the other components go, the entity gets the Destroyed tag and stays until a system removes the last cleanup componentCleanup and disable
Disabled<T>The tag an entity carries while its T is disabled: query it to find the paused onesCleanup and disable
DynamicBuffer<T>A list per entity, every write trackedDynamic buffers
ChildOf(EntityId Parent)The built-in hierarchy linkHierarchy
struct G : ISystemGroupA group of systems with its own cadenceSystems
: IGroupWith<T> / IGroupWithout<T> on a group (or an interface it implements)The group's systems visit only entities with / without T; a generic interface gives each actor type its own filtered groupSystems
class S<T> : EcsSystemA generic system: each closed type (S<Position>) is a system of its ownSystems

Components are structs (EECS006). Keep an entity link as an EntityId, not an Entity (EECS017).

World

CallDoes
new World(options)An isolated world; Dispose() runs every OnDestroy
world.Update()Runs the default group's systems once
world.Update<TGroup>()Runs one system group
world.AddSystem<T>() / AddSystem(instance)Adds a system (runs OnCreate)
world.RemoveSystem<T>() / GetSystem<T>() / SystemsRemoves, finds, lists systems
world.EntityCount / EntitiesLive entities and an allocation-free walk over them
world.ChangeTickThe current change tick
world.UpdateCountCompleted Update() calls of the default group
world.EnsureCapacity<T1, …, Tn>(n) / EnsureCapacity(prefab, n) / EnsureEntityCapacity(n)Pre-size before a known peak or a wave
world.TryGetEntity(id, out e) / GetEntity(id) / IsAlive(id)From an EntityId back to a checked handle
world.Describe()Tables, columns, rows and bytes, for tools

Entities

using var world = new World();
Entity unit = world.CreateEntity(new Position(0, 0), new Velocity(1, 0), new Health(100));

The generic calls, what the generated members call; code that names a component uses the members (unit.Velocity, SetHealth(50), RemoveDead()), as in the example under the table.

CallDoesStructural
world.CreateEntity(a, b, …)Creates with up to 9 components, straight into the final tableyes
entity.Set(a, b, …)Adds or overwrites up to 9 components in one move; returns the entityyes
entity.Remove<A, B>()Removes components it has; returns the entityyes
entity.GetOrAdd<T>()ref T, added with the default value if missingwhen added
entity.Get<T>()ref T for writing (a write for change tracking)no
entity.Read<T>()ref readonly T (never a write)no
entity.TryGet<T>(out T copy)A copy, if presentno
entity.TryGetRef<T>(out bool found)ref T or a null refno
entity.Has<T>() / Has<A, B>()Presence of one or allno
entity.Disable<T>() / Enable<T>() / IsDisabled<T>()Hides a component, keeping its valueyes
entity.Clone()A copy of the entity in its worldyes
entity.Run<T1..T9, TJob>(ref job) / Run(ref job, filter)Runs an IForEachEntity job on this entity with the refs a pass gives; false when it is not alive, lacks a component or fails the filterwhen the job makes one
entity.Destroy()Destroys it; its id is recycled with a new versionyes
entity.IsAlive / Id / WorldHandle state; every access checks the versionno
entity.Describe()Its component values, for debuggers and logsno
EntityId / EntityId.Null / id.IsNull / id.Index / id.VersionThe 8-byte id to keep in components; Null is the default valueno
unit.Velocity.X = 2;                                // write in place through the ref
float x = unit.Position.X;                          // a read (ref readonly for a tracked component)
unit.Set(new Health(50), new Dead());               // both in one call: shorter, same cost
unit.RemoveDead();                                  // flips a presence bit: the row stays
if (unit.TryGetHealth(out var hp)) { /* hp is a copy */ }
public struct TakeHit : IForEachEntity<Health>
{
    public int Damage;
    public static int Writes => 1;                  // bit 0: Health counts as written

    public void Execute(Entity target, ref Health hp) => hp.Value -= Damage;
}
var hit = new TakeHit { Damage = 30 };
bool applied = unit.Run<Health, TakeHit>(ref hit);   // a request handled on its entity

A ref stays valid until the next structural change and never across await (ref and await).

Generated members

The source generator gives every component, tag and singleton named members (C# 14 extension members). Each one is an inlined call to the generic API above.

DeclaredGenerated
Component Positione.Position (ref), HasPosition, TryGetPosition(out p), GetOrAddPosition(), SetPosition(x, y), RemovePosition(), DisablePosition(), EnablePosition(), IsPositionDisabled
Tracked or indexed Healthe.Health is ref readonly; write with SetHealth(…) or WriteHealth() (ref, tracked only)
Tag Deade.IsDead, SetDead(), RemoveDead()
Indexed Teamworld.TeamIndex (world.Index<Team, int>())
Grouped Zonefilter.InZone(id) (InGroup<Zone>(id))
Buffer element Loote.Loot (ref readonly DynamicBuffer<Loot>), HasLoot, WriteLoot(), GetOrAddLoot(), RemoveLoot()
Relation MemberOfe.AddMemberOf(target), RemoveMemberOf(target), LinksMemberOf(target), world.MemberOfIndex
Singleton Clockworld.Clock (ref), HasClock, GetOrAddClock(), SetClock(…), RemoveClock()
On a PrefabSetPosition(…), RemovePosition() return the prefab; prefab.Position (read-only), HasPosition, IsDead
world.Query<Position, Velocity>() itemsitem.Position, item.Velocity
unit.SetPosition(3, 4).SetDead();                   // setters return the entity
unit.Position.X += 1;                               // untracked: a ref
unit.SetHealth(80);                                 // tracked: written with Set, stamped
bool dead = unit.IsDead;

Systems and [ForEach]

MovementSystem.cs
public class MovementSystem : EcsSystem
{
    [ForEach, Without<Dead>]                         // once per entity with Position and Velocity, without Dead
    static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y);
}

[ForEach] parameters

ParameterIsNotes
ref TA component the method writes1 to 9 components; a write for change tracking
in TA component the method readsNot a write (EECS011 catches writes through in)
Span<T> / ReadOnlySpan<T>A run of rows of T (a batch method)Cannot mix with per-entity parameters (EECS009)
ref S / in SA singletonResolved once per pass; throws if it was not added
EntityThe current entityUse it for structural changes
WorldThe worldFor creating entities from a static method
EntitySpanThe entities of a batch method's runBatch methods only
Maybe<T>A component the entity may lackHasValue, Value
Any other type (outside a system)A value the caller passes to the entry pointref int count, in Settings s

Attributes

AttributeOnDoes
[ForEach] / [ForEach(Parallel = true)]MethodThe method is the loop; Parallel splits rows across threads (EECS010)
[With<T>]Method, system groupRequires T without passing it
[Without<T>]Method, system groupExcludes entities with T
[WithAny<A>, WithAny<B>]Method, system groupRequires at least one of them
[Changed<T>]MethodRows whose tracked T was written since the system last ran
[Removed<T>]MethodEntities that lost tracked T since the system last ran
[UpdateBefore<S>] / [UpdateAfter<S>]SystemOrdering (EECS019 rejects cycles)
[UpdateInGroup<G>]SystemRuns on world.Update<G>() only

[Changed<T>] and [Removed<T>] go on methods only. A system group takes [With<T>], [Without<T>] and [WithAny<T>] (EECS023 flags them on any other struct), or IGroupWith<T> / IGroupWithout<T>, which a generic group interface needs because an attribute cannot name a type parameter:

public struct In<TActor> : IComponent;              // the tag of one actor type
public interface IActorGroup<TActor> : IGroupWith<In<TActor>> where TActor : struct;
public struct Shop : IActorGroup<Shop>;             // the systems of [UpdateInGroup<Shop>] see In<Shop> entities only

System members

MemberDoes
OnCreate() / OnUpdate() / OnDestroy()Lifecycle; OnUpdate runs before the [ForEach] methods
WorldThe system's world
UpdateInterval / UpdatePhaseRun every N-th update, on phase 0 to N-1
EnabledSkip the system; setting true clears Error
ErrorThe exception that disabled it under SystemErrorPolicy.Disable
LastRunTickThe change tick of its last run
StatsRuns, Last, Total, Average with MeasureSystems

Systems keep no state (EECS007) and never reference each other (EECS008). Guide: Systems.

Queries and filters

// A field: build each filter once.
private static readonly QueryFilter Alive = QueryFilter.Create().Without<Dead>();
foreach (var item in world.Query<Position, Velocity>(Alive))
    item.Position.X += item.Velocity.X;             // items hand out refs; item.Entity is the handle

int movers = world.Count<Position, Velocity>(Alive);
bool anyDead = world.Any<Dead>();
CallDoes
world.Query<T1..T9>(filter)foreach over items: ref components and Entity
world.Count<T1..T9>(filter) / Any<…>(filter)Counts, or stops at the first match
world.ForEach<T1..T9, TJob>(ref job, filter)A struct job IForEach<T…>: Execute(ref T1 …)
world.ForEachEntity<…>(ref job, filter)IForEachEntity<T…>: Execute(Entity e, ref T1 …)
world.ForEachBatch<…>(ref job, filter)IForEachBatch<T…>: runs of rows as spans
world.ForEachParallel / ForEachEntityParallelA struct job in chunks on several threads
Runner.Method(world, …)The entry point of a static [ForEach] method outside a system
static int Writes => mask on a jobComponents the job writes (bit k - 1 for component k), stamped for change tracking; default -1, all
: INoStructuralChanges on a jobThe job promises no structural change: no per-entity bookkeeping, structure frozen while it runs
QueryFilterSelects
.With<T>() / .Without<T>() / .WithAny<T>()Presence, as the attributes
.Changed<T>(since) / .Removed<T>(since)Written, or lost, at or after tick since
.Since(tick)The same filter with a new tick
.InGroup<T>(group)One group of a grouped component

Singletons

CallDoes
world.AddSingleton<T>()Adds (or resets to default), returns ref T
world.GetSingleton<T>() / GetOrAddSingleton<T>()ref T; the first throws when missing
world.TryGetSingleton<T>(out copy) / HasSingleton<T>() / RemoveSingleton<T>()Copy, presence, removal
world.SingletonRef<T>()A stable handle: .Value is ref T
world.SetClock(0);                                  // generated: adds it if missing
world.Clock.Tick++;

Guide: Singletons.

Change tracking

Is a writeIs not a write
ref parameters, Span<T>, Query itemsin parameters, ReadOnlySpan<T>
Get<T>(), TryGetRef<T> when found, GetOrAdd<T>(), Set(…), WriteX()Read<T>(), TryGet<T>(out copy), Has<T>(), e.X of a tracked X
Creating, instantiating, cloning, Restore, Load, LoadEntitiesIntoRemoving (that is a removal, for [Removed<T>])
entity.Run: the components in the job's WritesLoadEntitiesInto(…, markWritten: false)
ulong mark = world.ChangeTick;
world.Update();
int changed = world.Count<Health>(QueryFilter.Create().Changed<Health>(mark));

Indexes, relations, hierarchy, groups

CallDoes
world.Index<T, TKey>() (world.TIndex)The value index of T
index.Find(key) / TryFind(key, out e) / Count(key)Matching entities, one, how many
index.Range(min, max) / RangeDescending / Ascending() / Descending()Sorted walks, for a comparable key
index.WhenTargetDestroyed(TargetPolicy.Keep / Remove / Destroy)What an EntityId link does when its target dies
entity.AddRelation(r) / RemoveRelation<T>(target) / HasRelation<T>(target)Many-to-many links
world.Relations<T>() then Find(target) / Count(target)Who links to a target
world.Children(parent)Entities whose ChildOf names the parent; destroying the parent destroys them (ChildOf starts with TargetPolicy.Destroy)
world.Descendants(root)The whole subtree, depth first, each entity before its children, root excluded; a ChildOf cycle throws InvalidOperationException
world.GroupBy<T>()Splits tables by an IGroup value
var teams = world.TeamIndex;
foreach (var member in teams.Find(1)) member.SetTeam(2);   // write indexed components with Set
var ship = world.CreateEntity();
world.CreateEntity(new ChildOf(ship));
foreach (var child in world.Children(ship)) { }
foreach (var part in world.Descendants(ship)) { }  // children, grandchildren, ...

Indexed and grouped components are written with Set, never through a ref (EECS015). Guides: Indexes and relations, Hierarchy, Groups.

Prefabs and bulk operations

CallDoes
new Prefab().SetX(…)… / new Prefab(basePrefab)A recipe outside every world, or a variant of one
prefab.AddMember() / prefab.IdA group of entities instantiated together; Id names a member in links
prefab.SetBuffer(items)A DynamicBuffer<T> each instance gets a copy of
world.Instantiate(prefab) / Instantiate(prefab, span)One entity, or a wave in one pass
world.CreateEntities(span, a, b, …)A wave with the same values
world.DestroyEntities<T…>(filter)Destroys every match; returns how many
world.SetAll(value, filter) / RemoveAll<T>(filter)One component set or removed on every match
world.DisableAll<T>(filter) / EnableAll<T>(filter)One component disabled or enabled on every match
var goblin = new Prefab().SetPosition(0, 0).SetHealth(30);
var wave = new Entity[100];
world.Instantiate(goblin, wave);
world.SetAll(new Velocity(0, 0), QueryFilter.Create().With<Health>());
world.DestroyEntities<Dead>();

Dynamic buffers

Reads go through e.Loot (ref readonly, with Count, Capacity, an indexer and foreach); writes take the buffer by ref from e.WriteLoot() (or GetOrAddLoot()), so each one counts for change tracking.

Call on ref DynamicBuffer<T>Does
Add(item) / AddRange(items) / Insert(index, item)Appends, appends a span, inserts
RemoveAt(index) / RemoveAtSwapBack(index)Removes keeping the order, or by moving the last element in (O(1))
Clear()Empties it, keeping the capacity
EnsureCapacity(n) / TrimExcess()Grows once before a known count, gives memory back
AsSpan()A Span<T> over the elements, for writes in place
unit.Set(new DynamicBuffer<Loot>());
ref var loot = ref unit.WriteLoot();
loot.EnsureCapacity(8);
loot.Add(new Loot(7));
loot.RemoveAtSwapBack(0);

Snapshots, saves, migration

CallDoes
world.Capture() / Capture(into)An in-memory copy; into reuses a snapshot's arrays
world.Restore(snapshot)Back to the copy; handles from then are valid again
world.Save(writer) / Load(bytes)A whole world as bytes (managed components need [NinoType]); Load throws InvalidDataException when an unmanaged component's layout changed since the save
world.SaveEntities(writer, ids) / LoadEntities(bytes, handles)A group of entities to another world or process
ComponentSet.Create().With<T>()…The components of a record, built once in a static readonly field
world.SaveEntities(writer, ids, set)A record: only the components of the set
world.LoadEntitiesInto(bytes, entities, markWritten: false)A record onto entities that exist; markWritten: false keeps it from counting as changed
world.MoveEntities(target, ids, moved)A group to another world of the thread, no encoding
world.RemoveTypes(assembly or context)Drops a plugin's types before its context unloads
var save = world.Capture();
world.Update();
world.Restore(save);

var bytes = new System.Buffers.ArrayBufferWriter<byte>();
world.Save(bytes);
using var copy = new World();
copy.Load(bytes.WrittenSpan);

World options

WorldOptionsDefaultDoes
InitialEntityCapacity1024Entity records allocated up front
ParallelSystemsfalseRuns systems with no order and no conflict at the same time
MaxDegreeOfParallelismprocessor countThreads one parallel run uses at most
MeasureSystemsfalseRecords system.Stats
SystemErrorsSystemErrorPolicy.ThrowDisable switches a failing system off and goes on
using var server = new World(new WorldOptions { ParallelSystems = true, SystemErrors = SystemErrorPolicy.Disable });

Guide: Threading.

Running it in a server and checking it: Hosting, Testing systems, Debugging and diagnostics.

Edit on GitHub

Last updated on

How is this guide?

On this page