EasyEcs

Common mistakes

Twenty-four mistakes people make with EasyEcs in C#, each with the code you might write, why it is wrong and the fix, plus the analyzer rule behind it.

Most of what goes wrong with EasyEcs comes from habits of object-oriented code or of other ECS libraries. The analyzer stops about half of these mistakes at compile time; the rest compile, run and quietly do the wrong thing. Each entry below is the code you might write, why it is wrong, and what to write instead.

Data

Changing a copy of a component

var hp = hero.Health;             // a copy of the row
hp.Value -= 10;                   // the table still holds the old value

The generated property returns a ref (as Get<T>() does), and var copies what it points at. Keep the ref, or write through the property directly:

ref var health = ref hero.Health;
health.Value -= 10;
hero.Health.Value -= 10;          // the same, inline

No rule catches it. More in copies and refs.

Storing an Entity in a component

public record struct Follow(Entity Leader) : IComponent;

An Entity holds a reference to its world: the column becomes managed (scanned by the GC, not copied as blocks), a save cannot write it and a migration does not rewrite it. Store the EntityId and look it up when you need it:

public record struct Follow(EntityId Leader) : IComponent;

Caught by EECS017 (warning). More in ids, versions and recycling.

Storing an index instead of an id

public record struct OwnerSlot(int Index) : IComponent;
var owned = world.CreateEntity(new OwnerSlot(hero.Id.Index));   // names whichever entity reuses that index

Ids are recycled: once the owner is destroyed, the index goes to the next entity created. An EntityId carries the version too, so TryGetEntity finds nothing once the owner is gone:

public record struct Owner(EntityId Id) : IComponent;
var item = world.CreateEntity(new Owner(hero.Id));
if (world.TryGetEntity(item.Owner.Id, out var owner)) { /* still alive */ }

No rule catches it. More in ids, versions and recycling.

A flag where a tag would do

public record struct Mobility(bool Rooted) : IComponent;

public class MoveRooted : EcsSystem
{
    [ForEach] static void Move(ref Position p, in Velocity v, in Mobility m)
    {
        if (m.Rooted) return;                  // every row is visited and tested
        p.X += v.X; p.Y += v.Y;
    }
}

A flag makes every system that cares visit every row and branch on it. A tag is a component with no fields: queries skip the whole table, and adding or removing it is the state change:

public struct Rooted : IComponent;

public class MoveFree : EcsSystem
{
    [ForEach, Without<Rooted>]                 // rooted entities are never visited
    static void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; }
}

For a state that flips every tick, a field is cheaper than a table move: see ECS principles, rule 5.

Removing a component to pause it

public record struct Cooldown(int Ticks) : IComponent;
var caster = world.CreateEntity(new Cooldown(30));
var kept = caster.Cooldown;             // stash the value somewhere
caster.RemoveCooldown();                // stunned
caster.Set(kept);                       // and put it back later

The value has to live somewhere in the meantime, and every reader of the stash is code you maintain. DisableCooldown() (Disable<T>()) hides the component from queries, Has and Get, keeps its value in the row, and EnableCooldown() brings it back:

caster.DisableCooldown();               // stunned: the cooldown is paused
caster.EnableCooldown();                // the stun ends: the same value

No rule catches it. More in disable a component.

A public Key => this on a record struct key

public readonly record struct Market(long Id) : IActor<Market>
{
    public Market Key => this;          // a public property: part of the record's ToString()
}

A record struct prints its public properties in ToString(). Key returns the record itself, which prints its Key, which prints its Key: the first log line or debugger view of the value overflows the stack. Implement Key explicitly, so it belongs to the interface only:

public readonly record struct Market(long Id) : IActor<Market>
{
    Market IIndexed<Market>.Key => this;
}

No rule catches it. The Actors sample shows the whole pattern.

Systems

State in a system

public class WaveSystem : EcsSystem
{
    private int _wave;
    protected override void OnUpdate() => _wave++;
}

Nothing else can read, save or snapshot that field, and it is lost when the system is removed. Per-world state is a singleton:

public record struct Wave(int Number) : ISingletonComponent;

public class WaveSystem : EcsSystem
{
    protected override void OnUpdate() => World.GetOrAddWave().Number++;
}

Caught by EECS007. More in ECS principles, rule 2.

A system that calls another

public class LootSystem : EcsSystem { }

public class KillRewards : EcsSystem
{
    protected override void OnUpdate() => World.GetSystem<LootSystem>();
}

Systems that call each other cannot be removed, reordered or tested alone. One writes data (a tag, a component, a singleton), and the other reads it, ordered after it:

public struct Looted : IComponent;

public class LootSystem : EcsSystem
{
    [ForEach, With<Dead>, Without<Looted>]
    static void Drop(Entity corpse) => corpse.SetLooted();
}

[UpdateAfter<LootSystem>]
public class KillRewards : EcsSystem
{
    [ForEach, With<Looted>]
    static void Reward(in Health hp) { }
}

Caught by EECS008. More in ECS principles, rule 3.

A ref parameter that only reads

public record struct Speed(float Value) : IComponent;
public class Throttle : EcsSystem
{
    [ForEach] static void Apply(ref Velocity v, ref Speed max)   // max is only read
    {
        v = new Velocity(Math.Min(v.X, max.Value), Math.Min(v.Y, max.Value));
    }
}

A ref parameter declares a write. With ParallelSystems, a system that writes Speed cannot share a stage with any other system that touches it, and if Speed were tracked, every row would count as changed. Read with in:

public class Throttle : EcsSystem
{
    [ForEach] static void Apply(ref Velocity v, in Speed max)
    {
        v = new Velocity(Math.Min(v.X, max.Value), Math.Min(v.Y, max.Value));
    }
}

Caught by EECS025 (warning, with a code fix). More in parallel systems.

[Changed<T>] on a component that is not tracked

public record struct Gold(int Amount) : IComponent;
public record struct Hud(int Gold) : IComponent;

public class ShowGold : EcsSystem
{
    [ForEach, Changed<Gold>] static void Show(in Gold gold, ref Hud hud) => hud = new Hud(gold.Amount);
}

Change ticks cost a column, so only components that ask for them have them. Mark the component ITrackChanges:

public record struct Gold(int Amount) : IComponent, ITrackChanges;
public record struct Hud(int Gold) : IComponent;

public class ShowGold : EcsSystem
{
    [ForEach, Changed<Gold>] static void Show(in Gold gold, ref Hud hud) => hud = new Hud(gold.Amount);
}

Caught by the C# compiler (the attribute requires ITrackChanges: CS0315). More in mark the component.

Reading a tracked component through a ref

int before = player.Get<Gold>().Amount;      // Get<T>() is a write: the row counts as changed

Get<T>() stamps the row, so every [Changed<Gold>] system visits it next update. Read with the generated property (it is ref readonly for a tracked component), Read<T>() in generic code, or an in parameter:

int amount = player.Gold.Amount;             // ref readonly: no stamp

Caught by EECS025 (warning, with a code fix). More in what counts as a write.

[Removed<T>] that takes T

public record struct Burning(int Ticks) : IComponent, ITrackChanges;
public record struct Glow(bool On) : IComponent;
public class Extinguish : EcsSystem
{
    [ForEach, Removed<Burning>] static void Out(in Burning burning, ref Glow glow) => glow = new Glow(false);
}

The entities [Removed<Burning>] visits no longer have Burning, so the method would never run. Read the row's other components:

public class Extinguish : EcsSystem
{
    [ForEach, Removed<Burning>] static void Out(ref Glow glow) => glow = new Glow(false);
}

Caught by EECS016. More in removal detection.

One hand-written group per actor type

public struct In<TActor> : IComponent;                  // the tag of one actor type
public readonly record struct Shop(long Id) : IComponent;
public readonly record struct Guild(long Id) : IComponent;
[With<In<Shop>>] public struct ShopGroup : ISystemGroup;      // one more struct for every actor type
[With<In<Guild>>] public struct GuildGroup : ISystemGroup;

Every new kind of actor needs its group written again, and a generic interface cannot carry the filter as an attribute: C# refuses a type parameter there ([With<In<TSelf>>] is CS8968). The interfaces IGroupWith<T> and IGroupWithout<T> can name it, so one generic interface makes each actor type its own key component, group and filter:

public interface IActor<TSelf> : IComponent, IIndexed<TSelf>, ISystemGroup, IGroupWith<In<TSelf>>
    where TSelf : struct, IActor<TSelf>, IEquatable<TSelf>;

public readonly record struct Shop(long Id) : IActor<Shop> { Shop IIndexed<Shop>.Key => this; }
public readonly record struct Guild(long Id) : IActor<Guild> { Guild IIndexed<Guild>.Key => this; }

No rule catches it. More in group filters.

Structure

Keeping a ref across a structural change

ref var life = ref hero.Health;
hero.SetStunned();                 // the row moves to another table
life.Value -= 10;                  // writes the old copy

Adding or removing a component moves the entity's row, and a ref taken before points at the old place. Get it again after the change:

hero.SetStunned();
hero.Health.Value -= 10;

No rule catches it. More in refs across a change.

Keeping a ref across an await

ref var stamina = ref hero.Health;
await Task.Delay(100);
stamina.Value -= 10;

The compiler refuses it (CS9217), and with reason: anything may happen to the row while the method waits. Keep the Entity and get the component again after the await, on the owner thread:

await Task.Delay(100);
if (hero.HasHealth) hero.Health.Value -= 10;

Caught by the C# compiler. More in across await.

Writing an indexed key through a ref

public record struct Zone(int Id) : IComponent, IIndexed<int> { public int Key => Id; }
public static class Portals
{
    public static void Enter(Entity player) => player.Get<Zone>() = new Zone(2);
}

The index follows Set; a write through a ref changes the key behind its back, and lookups keep finding the player in the old zone. Write it with Set or the generated SetX:

public static class Portals
{
    public static void Enter(Entity player) => player.SetZone(2);
}

Caught by EECS015. More in value indexes.

Copying a DynamicBuffer<T>

public record struct Loot(int Item);
public static class Inventory
{
    public static void Give(Entity player, Loot loot)
    {
        var bag = player.Read<DynamicBuffer<Loot>>();    // a copy that shares the list
        bag.Add(loot);                                   // the write is never stamped
    }
}

A buffer refers to its list: a copy writes to the same list without marking the entity changed, and storing it gives two entities one list. Reach it through the entity:

public static class Inventory
{
    public static void Give(Entity player, Loot loot)
    {
        ref var bag = ref player.Get<DynamicBuffer<Loot>>();
        bag.Add(loot);
    }
}

Caught by EECS012. More in dynamic buffers.

Destroying a parent and expecting the children to stay

var ship = world.CreateEntity(new Position(0, 0));
var turret = world.CreateEntity(new Position(1, 0), new ChildOf(ship));
ship.Destroy();                    // the turret is destroyed with it

ChildOf starts with TargetPolicy.Destroy: destroying a parent destroys its subtree. Choose what happens to the children once, for the world:

world.Index<ChildOf, EntityId>().WhenTargetDestroyed(TargetPolicy.Remove);   // orphans become roots

No rule catches it. More in cascade policy.

A loop of structural changes

public struct Fighter : IComponent;
foreach (var item in world.Query<Fighter>())
    item.Entity.SetFrozen();       // one structural change per entity

Each call moves one row. SetAll, RemoveAll, DisableAll and EnableAll move a table's rows together:

int frozen = world.SetAll(new Frozen(), QueryFilter.Create().With<Fighter>());

Caught by EECS030 (warning, with a code fix). More in bulk changes.

Collecting a subtree with Children alone

var subtree = new List<EntityId> { hero.Id };
foreach (var child in world.Children(hero)) subtree.Add(child.Id);   // grandchildren are left out

Children lists one level. A save or a move of that group leaves the grandchildren behind, and they die with the original. Descendants walks every level, depth first:

var group = new List<EntityId> { hero.Id };
foreach (var part in world.Descendants(hero)) group.Add(part.Id);   // children, grandchildren, ...

No rule catches it. More in moving a hierarchy.

Restoring a record that is then saved again

public record struct Bank(long Gold) : IComponent, ITrackChanges;   // persistent: saved when it changes
public record struct Connection(int Socket) : IComponent;           // runtime only
static Entity Activate(World world, ReadOnlySpan<byte> record)
{
    var actor = world.CreateEntity(new Connection(9), new Bank(0));  // a new actor's default
    world.LoadEntitiesInto(record, [actor]);                         // a write: the saver sends Bank back
    return actor;
}

A load counts as a write, so the system that saves or replicates [Changed<Bank>] rows writes the record straight back to where it came from, on every activation. Load it with markWritten: false: the stored Bank replaces the default and counts as never written, so the saver skips the actor until code changes it:

static Entity Restore(World world, ReadOnlySpan<byte> record)
{
    var actor = world.CreateEntity(new Connection(9), new Bank(0));  // the same default as a new actor
    world.LoadEntitiesInto(record, [actor], markWritten: false);     // Bank as stored, not a change
    return actor;
}

No rule catches it. More in records.

Threads

Changing a world from another thread

public static class Network
{
    public static void OnJoin(World world)
    {
        Task.Run(() => world.CreateEntity(new Position(0, 0)));
        world.CreateEntity(new Position(1, 1));
    }
}

A world's structure belongs to its owner thread, and the world adds no lock to share it. Put the input in a queue and let a system on the owner thread turn it into entities, or give each thread its own world.

Caught by EECS014. More in input from other threads.

A structural change in a parallel method

public class Reap : EcsSystem
{
    [ForEach(Parallel = true)]
    static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); }
}

Chunks of rows run on several threads at once, so none may move rows. Keep the parallel part to values, and let a sequential method change structure:

public class Reap : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); }
}

entity.Run in a parallel method

public struct Mend : IForEachEntity<Health>
{
    public static int Writes => 1;

    public void Execute(Entity target, ref Health hp) => hp.Value += 1;
}
public class HealAll : EcsSystem
{
    [ForEach(Parallel = true), With<Health>]
    static void Heal(Entity e)
    {
        var mend = new Mend();
        e.Run<Health, Mend>(ref mend);  // bookkeeping of the owner's pass, and the job may change structure
    }
}

entity.Run is for a request or a message to one entity, on the owner thread. It does the bookkeeping of the owner's pass and its job may change structure, so a parallel method cannot call it. A [ForEach] method already gets the refs a job would get; write through them:

public class HealAll : EcsSystem
{
    [ForEach(Parallel = true)]
    static void Heal(ref Health hp) => hp.Value += 1;
}

Caught by EECS010. More in one entity: entity.Run.

Edit on GitHub

Last updated on

How is this guide?

On this page