Analyzer rules
Every EasyEcs analyzer rule, EECS002 to EECS034, with its severity, its code fix, the code it rejects and the code to write instead.
The EasyEcs analyzer ships in the package next to the source generator, so code that breaks the ECS principles does not build. The correctness rules (EECS002 to EECS024) are errors except three warnings for code that works but costs (EECS017, EECS018, EECS020). The generator skips invalid input and the analyzer reports it, so "not generated" always means "reported". The performance rules (EECS025 to EECS034) find code that works and does more than it needs, and the severity says what kind (D29): a warning means the code costs (EECS025 to EECS032), a suggestion (Info) means the same cost written shorter (EECS033), and an error means code that cannot work (EECS034, a world update inside a system). Where a rule has one mechanical answer, the IDE offers it as a code fix (EasyEcs.CodeFixes, in the same package), and only when the result compiles.
When to read it
Read it for
A build error or warning whose id starts with EECS: jump to its section from the table below. Each section says
what the rule protects, the code it rejects, the fix and whether the IDE can apply it.
Do not
Suppress an EECS error with #pragma: the generator skipped the method or type the rule names, so the code it
needs does not exist. The warnings can be suppressed, at the cost they describe; a suggestion (Info) shows in the
IDE only, and dotnet_diagnostic.EECS033.severity = warning in .editorconfig raises one for a whole project.
All rules
| Id | Severity | Rule | Code fix |
|---|---|---|---|
| EECS002 | Error | Invalid [ForEach] parameter | in / ref for a component taken by value |
| EECS003 | Error | A [ForEach] method takes 1 to 9 components, or none with a [With<T>] or [Changed<T>] | |
| EECS004 | Error | A system's [ForEach] method is not generic | |
| EECS005 | Error | An instance [ForEach] method belongs to a system | Make it static |
| EECS006 | Error | Components and singletons are structs | Make it a struct |
| EECS007 | Error | Systems are stateless | |
| EECS008 | Error | Systems do not reference systems | |
| EECS009 | Error | A batch [ForEach] method takes only spans, singletons and an EntitySpan | |
| EECS010 | Error | A [ForEach(Parallel = true)] method can run on several threads | Run it on one thread |
| EECS011 | Error | A [ForEach] method does not change what a read-only parameter holds | Take it by ref |
| EECS012 | Error | A DynamicBuffer<T> is never copied | in, or ref with the callers |
| EECS013 | Error | A [ForEach] method that takes no Entity or World changes no structure | |
| EECS014 | Error | Structural changes stay on the world's owner thread | |
| EECS015 | Error | An indexed component is written with Set | |
| EECS016 | Error | A [Removed<T>] method does not require T | |
| EECS017 | Warning | Components store an EntityId, not an Entity | |
| EECS018 | Warning | UpdateInterval and UpdatePhase are constants | |
| EECS019 | Error | Systems are not ordered in a cycle | |
| EECS020 | Warning | Systems are ordered within their group | |
| EECS021 | Error | A [ForEach] entry point does not collide with a method | |
| EECS022 | Error | The generated code can name a [ForEach] method's types | Make it internal |
| EECS023 | Error | Filters go on [ForEach] methods and system groups | Remove the filter |
| EECS024 | Error | [ForEach] is not on a local function | |
| EECS025 | Warning | A write access only reads | in, ReadOnlySpan<T>, Read<T>() |
| EECS026 | Warning | A [ForEach] method uses its parameters | [With<T>], or remove the parameter |
| EECS027 | Warning | A [ForEach] method takes what it looks up on every row | |
| EECS028 | Warning | Code that runs every update does not allocate | |
| EECS029 | Warning | An instance [ForEach] method uses its system | Make it static |
| EECS030 | Warning | A structural change over a query is one bulk call | The bulk call |
| EECS031 | Warning | Entities created in a counted loop are created together, or reserved | CreateEntities, EnsureCapacity |
| EECS032 | Warning | The world counts and filters | Any, Count |
| EECS033 | Info | A generated member says it shorter | The generated member |
| EECS034 | Error | A system does not run a world update |
EECS002
Invalid [ForEach] parameter. Error. Code fix: adds in or ref to a component or singleton taken by value.
Every parameter must be a ref / in / ref readonly struct implementing IComponent or ISingletonComponent, a
Span<T> / ReadOnlySpan<T> of an IComponent struct, a Maybe<T> of one (an optional component), an Entity, or
the World. A [ForEach] method outside a system may also take
values of any other type: its generated entry point takes them from the caller.
public class MoveSystem : EcsSystem
{
[ForEach] static void Move(ref Position p, float dt) { } // a system's method gets no caller's value
}Pass components and singletons by ref (write) or in / ref readonly (read), and turn other values into data:
public record struct DeltaTime(float Seconds) : ISingletonComponent; // the value becomes a singleton
public class MoveSystem : EcsSystem
{
[ForEach]
static void Move(ref Position p, in Velocity v, in DeltaTime dt)
{
p.X += v.X * dt.Seconds;
p.Y += v.Y * dt.Seconds;
}
}EECS003
Invalid component count. Error. No code fix.
A [ForEach] method takes between 1 and 9 components (singletons, Entity, World and a runner's other values do
not count; a Maybe<T> does), or none when a [With<T>] (else a [Changed<T>]) names the component to query.
[Removed<T>] names none: the entities it selects no longer have T, so the method also needs a component parameter
or a [With<U>].
public class CorpseCleanupSystem : EcsSystem
{
[ForEach] static void Remove(Entity e) => e.Destroy(); // which entities? no component names them
}Name the component with a filter. With no component at all, use OnUpdate; with more than 9, move the extra
requirements to [With<T>] or split the method:
public class CorpseCleanupSystem : EcsSystem
{
[ForEach, With<Dead>] // the filter names what to query
static void Remove(Entity e) => e.Destroy();
}EECS004
Generic [ForEach] method in a system. Error. No code fix.
A system runs its [ForEach] methods itself, once per update, so a generic method would get no type arguments.
Generic systems are fine (each closed type is a system of its own), and so are generic [ForEach] methods outside
systems, whose entry points take the type arguments from the caller.
public class ClampSystem : EcsSystem
{
[ForEach] static void Clamp<T>(ref T value) where T : struct, IComponent { } // which T?
}Make the system generic instead of the method:
public interface IClamped { int Value { get; set; } }
public class ClampSystem<T> : EcsSystem where T : struct, IComponent, IClamped // AddSystem<ClampSystem<Armor>>()
{
[ForEach] static void Clamp(ref T value) => value.Value = Math.Max(value.Value, 0);
}EECS005
Instance [ForEach] method outside a system. Error. Code fix: makes the method static, when its body uses no
instance member.
A [ForEach] method of a type that is no EcsSystem gets a generated entry point that takes the world
(Physics.Move(world)), and there is no instance to call the method on.
public class Physics
{
[ForEach] void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; } // on which Physics?
}Make it static, or move it into a system:
public static class Physics // Physics.Move(world) runs it once over the world
{
[ForEach] public static void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; }
}EECS006
ECS data must be a struct. Error. Code fix: changes the class to a struct, for a class declared once, with no base
class and no member a struct cannot have (protected, virtual, abstract, a finalizer).
Components and singletons are stored by value in columns. Interfaces may extend the markers; classes may not implement them.
public class Wallet : IComponent { public int Gold; }public record struct Wallet(int Gold) : IComponent;EECS007
Systems must be stateless. Error. No code fix.
A system has a mutable field, a settable auto-property or a field-like event (static ones included), or a member
writes a primary-constructor parameter (a hidden field). State in a system is invisible to other systems, queries and
saves, it is lost or duplicated when the system is removed or added again, and a static one is shared by every world.
readonly fields (dependencies, reusable scratch buffers), init-only properties and computed properties are
allowed.
public class SpawnSystem : EcsSystem
{
private int _spawned; // state no one else can see or save
protected override void OnUpdate() => _spawned++;
}Move per-entity state into a component and per-world state into a singleton:
public record struct Spawned(int Count) : ISingletonComponent;
public class SpawnSystem : EcsSystem
{
protected override void OnUpdate() => World.GetOrAddSpawned().Count++;
}EECS008
Systems must not reference systems. Error. No code fix.
A field, auto-property, event or primary-constructor parameter of a system has a system type (an array of systems or
a type argument included), or a system looks another one up with World.GetSystem<T>(). Systems that call each other
are coupled: neither can be removed, reordered or tested alone. GetSystem is for tools, tests and the code that
hosts the world.
public class KillSystem : EcsSystem { }
public class ScoreSystem(KillSystem kills) : EcsSystem
{
private readonly KillSystem _kills = kills; // the two can no longer change apart
}Write the data the other system reads (a component or a singleton) and order the two (ECS principles, rule 3):
public record struct Score(int Deaths) : ISingletonComponent;
public class KillSystem : EcsSystem
{
[ForEach, Without<Dead>]
static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); }
}
[UpdateAfter<KillSystem>] // it reads the Dead that KillSystem wrote
public sealed class ScoreSystem : EcsSystem
{
// One pass destroys the corpses and says how many there were: each is counted once.
protected override void OnUpdate() => World.GetOrAddScore().Deaths += World.DestroyEntities<Dead>();
}EECS009
Batch [ForEach] mixes spans and per-entity parameters. Error. No code fix.
A method that takes component spans receives whole runs of rows, so a per-entity parameter (a ref / in component,
an Entity) has no single value for the call, and the World could change rows while the spans point into them. An
EntitySpan without component spans has no run to describe.
public class DriftAllSystem : EcsSystem
{
[ForEach] static void Drift(Span<Position> p, in Velocity v) { } // v has no single value for a run of rows
}Take every component as a span (Span<T> to write, ReadOnlySpan<T> to read), singletons besides, and an
EntitySpan for the run's entities; or write a per-entity method:
public class DriftAllSystem : EcsSystem
{
[ForEach]
static void Drift(Span<Position> p, ReadOnlySpan<Velocity> v) // element i of both spans is one entity
{
for (int i = 0; i < p.Length; i++)
{
p[i].X += v[i].X;
p[i].Y += v[i].Y;
}
}
}EECS010
[ForEach(Parallel = true)] cannot run on several threads. Error. Code fix: removes Parallel = true.
A parallel method runs chunks of rows on several threads at once, so it must make no structural change (static, no
World, its Entity used only to read: Id, Has, Get, ...; not entity.Run, which does the owner's pass
bookkeeping and whose job may change structure), run per entity (not a batch method) and write no singleton (a ref
singleton would race between chunks).
public class KillSystem : EcsSystem
{
[ForEach(Parallel = true)]
static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); } // a structural change
}Take singletons as in, move structural changes into a sequential system that reacts to data the parallel one
writes, or drop Parallel = true:
public record struct Regen(int PerTick) : ISingletonComponent;
public class RegenSystem : EcsSystem
{
[ForEach(Parallel = true), Without<Dead>]
static void Regenerate(ref Health hp, in Regen regen) => hp.Value += regen.PerTick; // reads the singleton only
}EECS011
Write through a read-only parameter. Error. Code fix: takes the parameter by ref (a ReadOnlySpan<T> becomes a
Span<T>); none for a singleton of a parallel method, since a ref singleton there is EECS010.
A [ForEach] method takes a component or singleton as in (or a component as ReadOnlySpan<T>) and changes data it
holds by reference: it calls a mutating method on a collection (Add, Remove, Clear, Insert, Push,
Enqueue, Sort, ...), assigns an element (grid.Cells[i] = x) or a member of a class it holds
(holder.Owner.Gold++). The compiler allows it because only the reference is read-only, but the write is scheduled as
a read (parallel systems that read the same data race with it) and never stamped, so [Changed<T>] systems and value
indexes miss it.
public record struct Grid(List<int> Cells) : ISingletonComponent;
public class GridSystem : EcsSystem
{
[ForEach] static void Mark(in Position p, in Grid grid) => grid.Cells.Add((int)p.X); // 'in', but written
}public record struct Grid(List<int> Cells) : ISingletonComponent;
public class GridSystem : EcsSystem
{
[ForEach] static void Mark(in Position p, ref Grid grid) => grid.Cells.Add((int)p.X); // ref: scheduled as a write
}Calls that return a new value (string, immutable and frozen collections) are reads. The rule sees changes made
directly on the parameter's members; a reference copied into a local, or changed inside a method of your own class,
is not followed. Collections in components are allowed;
ECS principles, rule 8 says when to prefer entities.
EECS012
DynamicBuffer<T> held by value. Error. Code fix: adds in, or ref together with each caller's argument when
every caller passes a variable; none for an override or an interface's method, whose signature is shared.
A DynamicBuffer<T> refers to its list, so a copy of the value refers to the same
list: writes through the copy are never stamped as changed, and storing the copy gives a second entity (or a snapshot)
the same list. The rule reports a DynamicBuffer<T> field or property, a by-value parameter or return, a local that
is not a ref local, an assignment of an existing buffer, and an existing buffer passed to Set, CreateEntity or
another generic method that stores it.
public record struct Loot(int Item);public static class Bags
{
public static void Share(Entity player, Entity other)
{
var bag = player.Read<DynamicBuffer<Loot>>(); // a copy
other.Set(player.Read<DynamicBuffer<Loot>>()); // two entities, one list
}
}Reach the buffer through its entity: ref / in parameters, ref var bag = ref entity.Get<DynamicBuffer<T>>(),
entity.Read<DynamicBuffer<T>>(). A new component value is new DynamicBuffer<T>() (or default), which holds no
list; a prefab gets its elements with SetBuffer(…) or the generated SetLoot(…):
public static class Bags
{
public static int Items(Entity player) => player.Read<DynamicBuffer<Loot>>().Count; // read through the entity
public static void Give(Entity player, Loot loot)
{
ref var bag = ref player.Get<DynamicBuffer<Loot>>(); // a ref local: a tracked write
bag.Add(loot);
}
public static Entity Spawn(World world) => world.CreateEntity(new DynamicBuffer<Loot>()); // a new, empty buffer
}EECS013
Structural change in a [ForEach] method that promises none. Error. No code fix.
A [ForEach] method that is static and takes no Entity or World (or uses its Entity only to read) cannot change
structure as far as the generator can see, so it walks the rows without re-checking storage after each call, and the
system shares a parallel stage with other systems. A structural change
made anyway, through a handle or a world kept elsewhere, breaks both: the pass keeps refs into rows that moved, and a
change inside a parallel stage throws.
The rule reports a call to a structural member of Entity (Set, Remove, Destroy, GetOrAdd, Clone,
Disable, Enable, AddRelation, RemoveRelation, Run (its job may change structure), and the generated SetX, GetOrAddX, RemoveX) or World
(CreateEntity, CreateEntities, Instantiate, DestroyEntities, SetAll, RemoveAll, DisableAll,
EnableAll, Load, LoadEntities, LoadEntitiesInto, MoveEntities, GroupBy, RemoveTypes, singletons, systems, Update,
Capture, Restore, ...) in such a method. A world the method creates itself (new World() in a local) is its own.
public record struct Target(EntityId Id) : IComponent;
public struct Doomed : IComponent; // a tag
public static class Arena { public static readonly World Main = new(); }public class SpawnEffects : EcsSystem
{
[ForEach] static void Spawn(in Position p) => Arena.Main.CreateEntity(p); // no Entity or World parameter
}Take the Entity or the World as a parameter and make the change through it (the system then runs alone, with a
pass that notices the change), or record the change as data for a system that makes it:
public class MarkTargets : EcsSystem
{
[ForEach, With<Target>]
static void Mark(Entity hunter, in Target target, World world)
{
hunter.RemoveTarget(); // through the parameter: this system runs alone
if (world.TryGetEntity(target.Id, out var prey)) prey.SetDoomed(); // and its pass notices this one too
}
}The rule sees the method's own body: a change made in a helper method it calls is not followed. Inside a parallel
stage or a parallel [ForEach] the runtime still throws for it
(what the world synchronizes).
EECS014
Structural change on another thread. Error. No code fix.
A world's structure belongs to its owner thread. The rule reports a structural call (the members EECS013 lists) in a
lambda or anonymous method handed to Task.Run, TaskFactory.StartNew, new Task, Parallel.*,
ThreadPool.QueueUserWorkItem (and its relatives), new Thread or new Timer, when the world or entity it changes
can be changed by another thread at the same time:
Parallel.*runs the delegate on several threads at once, so any world or entity captured from outside it races (worlds[i], a world per item, does not);- the hand-off sits in a loop, so the delegate runs several times over the same captured world or entity;
- the code around the hand-off (the method, or the type for a field) changes the same world's structure too.
public static class Spawner
{
public static void Start(World world, Entity[] players)
{
Task.Run(() => world.CreateEntity(new Position(0, 0))); // the caller changes this world too
world.CreateEntity(new Position(1, 1));
Parallel.For(0, players.Length, i => players[i].Destroy()); // entities of one world, several threads at once
}
}A world handed to a thread that then owns it (a world per thread, a world created inside the delegate) is not
reported, and neither is a hand-off the caller waits for at once (await, Wait(), Result,
GetAwaiter().GetResult()): nothing runs beside it. Hand the change to the owner thread as data, through a queue its
system drains (input from other threads), or give the other
thread its own world:
public static class WorldThreads
{
// A world per thread: each thread owns its world, nothing is shared.
public static Thread[] Start(World[] worlds)
{
var threads = new Thread[worlds.Length];
for (int i = 0; i < worlds.Length; i++)
{
var zone = worlds[i]; // one variable per iteration
threads[i] = new Thread(() => { for (int t = 0; t < 1_000; t++) zone.Update(); });
threads[i].Start();
}
return threads;
}
}Like EECS013, the rule sees the delegate's own body, and a receiver it cannot follow (a method's result) is not reported.
EECS015
Indexed component written through a ref. Error. No code fix.
A value index follows Set, CreateEntity and
CreateEntities; a write through a ref changes the key behind its back. For a component implementing
IIndexed<TKey> (or IGroup, whose group is a key too), the rule reports:
Get<T>(),GetOrAdd<T>()orTryGetRef<T>()on an entity;- a
reflocal bound to it, or an assignment to it (or a field of it) through a query item; - a
reforSpan<T>parameter of it in a[ForEach]method or anIForEach*job.
public record struct Zone(int Id) : IComponent, IIndexed<int> { public int Key => Id; }
public record struct Portal(int To) : IComponent;public class TakePortals : EcsSystem
{
[ForEach] static void Take(ref Zone zone, in Portal portal) => zone = new Zone(portal.To); // the index keeps the old zone
}Read it with in, ReadOnlySpan<T>, Read<T>() or the generated property, and write it with Set (or the
generated SetX):
public class TakePortals : EcsSystem
{
[ForEach]
static void Take(Entity player, in Zone zone, in Portal portal)
{
if (zone.Id != portal.To) player.SetZone(portal.To); // a Set: the index moves the player at once
}
}EECS016
[Removed<T>] method that requires T. Error. No code fix.
[Removed<T>] visits entities that lost T and still lack it. Taking T as a parameter, or requiring it with
[With<T>] or [Changed<T>] on the same method, asks for entities that have T: no row passes both, so the method
would never run.
public record struct Burning(int Ticks) : IComponent, ITrackChanges;
public record struct Replica(int Health, bool Burning) : IComponent;public class ReplicateFire : EcsSystem
{
[ForEach, Removed<Burning>]
static void Out(in Burning burning, ref Replica replica) => replica.Burning = false; // the entity lacks Burning
}Read the entity's other components (the row keeps them), and handle "added again" or "written" in another method with
[Changed<T>]:
public class ReplicateFire : EcsSystem
{
[ForEach, Changed<Burning>]
static void Lit(ref Replica replica) => replica.Burning = true;
[ForEach, Removed<Burning>] // the other components of the row are still there
static void Out(ref Replica replica) => replica.Burning = false;
}EECS017
A component stores an Entity handle. Warning. No code fix.
public record struct Chase(Entity Prey) : IComponent; // a managed columnStore the EntityId (8 bytes, unmanaged; a handle converts to it implicitly) and turn it back into a handle with
world.TryGetEntity(id, out var entity), which also says whether the entity still lives:
public record struct Chase(EntityId Prey) : IComponent;
public class ChaseSystem : EcsSystem
{
[ForEach]
static void Follow(ref Position p, in Chase chase, World world)
{
if (world.TryGetEntity(chase.Prey, out var prey)) p = prey.Position; // gone: the id finds nothing
}
}EECS018
A system's schedule is not a constant. Warning. No code fix.
UpdateInterval and UpdatePhase are read every update, so a value that changes makes the system skip or repeat
runs.
public class SaveSystem : EcsSystem
{
public override int UpdateInterval => World.EntityCount > 1000 ? 4 : 1;
}Return a constant. To stop and resume a system, set Enabled:
public class SaveSystem : EcsSystem
{
public override int UpdateInterval => 60; // every 60th update
public override int UpdatePhase => 30; // half a cycle after the others with the same interval
}EECS019
Systems ordered in a cycle. Error. No code fix.
[UpdateBefore<T>] and [UpdateAfter<T>] say which of two systems runs first; a cycle cannot hold, and AddSystem
throws when the system that closes it is added. The analyzer reports the cycles it sees between the systems of the
compilation.
[UpdateAfter<B>] public class A : EcsSystem { }
[UpdateAfter<A>] public class B : EcsSystem { } // A after B after ARemove one of the orderings:
public class Movement : EcsSystem { }
[UpdateAfter<Movement>] public class Collision : EcsSystem { }
[UpdateAfter<Collision>] public class Damage : EcsSystem { }EECS020
A system ordered against another group. Warning. No code fix.
Orderings apply within one group: World.Update() and World.Update<TGroup>() run their groups separately, in the
order the caller calls them, so an ordering against a system of another group never applies.
public struct Late : ISystemGroup;
[UpdateInGroup<Late>] public class Sweep : EcsSystem { }
[UpdateAfter<Sweep>] public class Movement : EcsSystem { } // Movement runs in the default groupOrder systems of one group, or move the system into the other's group:
public struct Late : ISystemGroup;
[UpdateInGroup<Late>] public class Sweep : EcsSystem { }
[UpdateInGroup<Late>, UpdateAfter<Sweep>] public class Recycle : EcsSystem { }EECS021
A [ForEach] entry point has the signature of another method. Error. No code fix.
Outside a system, the generator writes an overload of each [ForEach] method that takes the World (and the change
tick, for [Changed<T>] / [Removed<T>]) followed by the method's other values. If the type already has a method
with that signature, or another [ForEach] overload's entry point has it, the two collide.
public static class Healing
{
[ForEach] static void Heal(ref Health hp) => hp.Value++;
public static void Heal(World world) { } // the entry point Heal(World) exists already
}Rename one of them:
public static class Healing
{
[ForEach] static void Heal(ref Health hp) => hp.Value++; // Healing.Heal(world)
public static void HealAll(World world) => Healing.Heal(world); // the generated entry point
}EECS022
A type out of reach of the generated code. Error. Code fix: makes the type internal, with every private or protected type that contains it, in each part of a partial type that states an accessibility.
The generator writes the jobs of [ForEach] methods outside the user's type and calls the methods through
UnsafeAccessor, so private methods and private systems are fine. The types of the parameters (and return), and the
type of a [ForEach] method outside a system, must be internal or public, as must every type containing them; a
file type is out of reach of any other file.
public class HealSystem : EcsSystem
{
private struct Regen : IComponent { public int Amount; } // the generated job cannot name it
[ForEach] static void Heal(ref Health hp, in Regen r) => hp.Value += r.Amount;
}public class HealSystem : EcsSystem
{
internal struct Regen : IComponent { public int Amount; }
[ForEach] static void Heal(ref Health hp, in Regen r) => hp.Value += r.Amount;
}EECS023
A filter on a struct that is no system group. Error. Code fix: removes the filter.
[With<T>], [Without<T>] and [WithAny<T>] on an ISystemGroup struct join every [ForEach] method of the
group's systems. On any other struct, such as a component, they do nothing.
[Without<Dead>] public struct Armor : IComponent { public int Value; } // filters nothingPut the filter on the methods, or on their group:
public struct Armor : IComponent, IClamped { public int Value { get; set; } }
[Without<Dead>] public struct Alive : ISystemGroup; // every [ForEach] of the group skips Dead entitiesEECS024
[ForEach] on a local function. Error. No code fix.
The generator writes a job for each [ForEach] method and calls it from outside its type; a local function has no
name outside its method.
public static class Report
{
public static int Alive(World world)
{
int alive = 0;
[ForEach, With<Health>] static void Count(ref int alive) => alive++; // nothing can call it
return alive;
}
}Make it a method of a system, or a static method of a type (its entry point takes the world):
public static class Report
{
[ForEach, With<Health>] static void Count(ref int alive) => alive++;
public static int Alive(World world)
{
int alive = 0;
Report.Count(world, ref alive); // the generated entry point
return alive;
}
}EECS025
A write access that only reads. Warning. Code fix: in for a component or singleton, ReadOnlySpan<T> for a
span, Read<T>() for Get<T>(), .X for WriteX().
A ref parameter (a Span<T> in a batch method) puts its type in the system's write set: no
parallel stage runs the system beside one that reads the type. On a
tracked component it also stamps every row the method visits, so [Changed<T>]
systems visit rows nobody changed. entity.Get<T>() and the generated entity.WriteX() stamp the row the same way.
The rule looks at every use: an assignment, ++, a ref or out argument, a method that is not readonly, a ref
local or a this ref extension (DynamicBuffer<T>.Add) is a write, and keeps the access.
public record struct Armor(int Value) : IComponent, ITrackChanges;public class ArmorBonus : EcsSystem
{
[ForEach]
static void Apply(ref Armor armor, ref Health health) => health = new Health(health.Value + armor.Value); // armor is only read
}Read it by in:
public class ArmorBonus : EcsSystem
{
[ForEach]
static void Apply(in Armor armor, ref Health health) => health = new Health(health.Value + armor.Value);
}EECS026
A [ForEach] parameter the method does not use. Warning. Code fix: a component becomes a [With<T>] filter (or
goes, when a [With<T>] or [Changed<T>] already requires it); an Entity, World, EntitySpan, singleton or
Maybe<T> goes.
Each parameter costs something on every row or every pass: a component's column is loaded and advanced, a singleton is
resolved and scheduled as an access, an Entity builds a handle for every row and, like the World, makes the system
run alone. A component the method only requires is a filter. An unused
ref of a tracked component is reported without a fix: it stamps every row it visits, and [With<T>] would not.
A method with an empty body is left alone while it is being written.
public record struct Survivors(int Count) : ISingletonComponent;public class CountSurvivors : EcsSystem
{
[ForEach, Without<Dead>]
static void Count(in Health health, ref Survivors survivors) => survivors = new Survivors(survivors.Count + 1);
}Require the component with a filter:
public class CountSurvivors : EcsSystem
{
[ForEach, With<Health>, Without<Dead>]
static void Count(ref Survivors survivors) => survivors = new Survivors(survivors.Count + 1);
}EECS027
A lookup per row that a parameter makes once. Warning. No code fix.
A [ForEach] method's parameters are resolved once per table or per pass: a component is a column the loop walks, a
singleton a ref taken before the loop. The same data looked up through the visited Entity (entity.Velocity,
entity.Has<T>(), entity.TryGet<T>(...)) or through the World (World.Clock) repeats the search on every row:
the entity's record, its table, the column. The rule reports only lookups that run on every row (not in a branch,
a loop or after an early return), of components the method does not add or remove itself, and not of indexed
components.
public class Drift : EcsSystem
{
[ForEach]
static void Move(Entity entity, ref Position position) =>
position = new Position(position.X + entity.Velocity.X, position.Y + entity.Velocity.Y);
}Take the component as a parameter (in, ref, or Maybe<T> when some entities lack it; a presence test is a
Maybe<T> or a [With<T>] / [Without<T>] split), and a singleton as a parameter too:
public class Drift : EcsSystem
{
[ForEach]
static void Move(ref Position position, in Velocity velocity) =>
position = new Position(position.X + velocity.X, position.Y + velocity.Y);
}EECS028
An allocation in code that runs every update. Warning. No code fix.
A [ForEach] method runs for every entity it visits and OnUpdate once per update, so what they allocate is garbage
of every tick, and the collections it causes pause the world. The rule names each allocating expression: an object or
array, a lambda that captures, a method group of an instance, LINQ, a string built at run time ($"...", +,
string.Format, ToString()), boxing, and foreach over an interface. Left out: code inside a throw, calls the
compiler removes ([Conditional], such as Debug.Assert), console output (the write costs more than its string),
and the OnUpdate of a system that overrides UpdateInterval (its author chose that cadence).
public class Steer : EcsSystem
{
[ForEach]
static void Aim(in Position position, ref Velocity velocity)
{
var path = new List<Position> { position }; // a list for every entity, every update
velocity = new Velocity(-path[0].X, -path[0].Y);
}
}Keep values in structs, spans and stackalloc; keep a reusable collection in a component or a singleton taken by
ref; pass numbers, not strings:
public class Steer : EcsSystem
{
[ForEach]
static void Aim(in Position position, ref Velocity velocity)
{
Span<Position> path = stackalloc Position[1];
path[0] = position;
velocity = new Velocity(-path[0].X, -path[0].Y);
}
}EECS029
An instance [ForEach] method that uses no instance member. Warning. Code fix: makes it static.
An instance method could reach the World through its system, so the generator treats it as one that may change
structure: its system runs alone in a parallel stage, and its rows are walked with the checks a structural change
needs. A static method that takes no Entity or World is proven not to change structure
(EECS013).
public class MoveSystem : EcsSystem
{
[ForEach]
void Move(ref Position position, in Velocity velocity) =>
position = new Position(position.X + velocity.X, position.Y + velocity.Y);
}Make it static:
public class MoveSystem : EcsSystem
{
[ForEach]
static void Move(ref Position position, in Velocity velocity) =>
position = new Position(position.X + velocity.X, position.Y + velocity.Y);
}EECS030
A structural change entity by entity over a query. Warning. Code fix: the bulk call.
A structural change through each entity of a query moves (or flips) one row per call, through the structural gate each
time. SetAll, RemoveAll, DisableAll, EnableAll and DestroyEntities change every matching row of a table
together, whole words of rows at once (bulk changes). The rule
reports a foreach over world.Query<...>() whose body is one such call on the item's entity with the same value for
every row. A Set of a component the query already requires writes a value instead of moving a row, and is left alone.
foreach (var item in world.Query<Health>(QueryFilter.Create().With<Dead>()))
item.Entity.Destroy();One call:
world.DestroyEntities<Health>(QueryFilter.Create().With<Dead>());EECS031
Entities created one by one in a counted loop. Warning. Code fix: the bulk call, or a reservation before the loop.
Created one by one, a table and the entity storage grow by doubling, and in a world that has never held them the
discarded arrays can set off a full garbage collection (D28).
CreateEntities and Instantiate(prefab, span) create them in one pass; EnsureCapacity reserves room when each
entity gets values of its own. The rule leaves out loops of a constant count under 4,096, or over an array created
with one (no array reaches the large object heap), loops after a reservation, loops that create only under a branch or
in an inner loop, and loops in a system (a running world reuses its rows).
var wave = new Entity[50_000];
for (int i = 0; i < wave.Length; i++)
wave[i] = world.CreateEntity(new Position(0, 0), new Health(100));One call when the values are the same; a reservation when they are not:
var spawned = new Entity[50_000];
world.CreateEntities(spawned, new Position(0, 0), new Health(100));
world.EnsureCapacity<Position, Health>(spawned.Length);
for (int i = 0; i < spawned.Length; i++)
world.CreateEntity(new Position(i, 0), new Health(100));EECS032
Query work the world does in one call. Warning. Code fix: Any, or Count for a loop that only counts.
Count sums the row counts of the matching tables and Any stops at the first table with a row; neither visits a
row. A filter skips whole tables and words of rows that a test in the loop visits one by one. The rule reports
Count<...>() compared with 0 or 1 as a presence test, a foreach over a query that only counts, and a loop whose
first statement skips rows by a component test of the item's entity (no fix: the filter goes where the query is made).
bool anyDead = world.Count<Dead>() > 0;bool someoneDied = world.Any<Dead>();
foreach (var item in world.Query<Health>(QueryFilter.Create().With<Burning>())) { } // the filter, not a test in the loopEECS033
A generic call with a generated member of the same meaning. Info. Code fix: the generated member.
The generator writes named members for every component, singleton,
buffer element and query shape, each calling the generic API: the same call at the same cost, which is why this rule
is a suggestion and not a warning. The rule offers the member only where it is generated in
that compilation and does the same thing, including the kind of reference it returns: Get<T>() of a tracked
component becomes WriteX() (its entity.X is read-only), and a buffer's member is offered only while other code
still names DynamicBuffer<T> (the generator writes buffer members for the elements code names that way).
| Generic | Generated |
|---|---|
entity.Get<Health>(), entity.Read<Health>() | entity.Health (or WriteHealth() for a tracked component) |
entity.Has<Health>(), entity.Has<Dead>() | entity.HasHealth, entity.IsDead |
entity.TryGet<Health>(out h), entity.GetOrAdd<Health>() | entity.TryGetHealth(out h), entity.GetOrAddHealth() |
entity.Set(new Health(100)), entity.Set(new Dead()) | entity.SetHealth(100), entity.SetDead() |
entity.Remove<Health>(), Disable<T>(), Enable<T>(), IsDisabled<T>() | entity.RemoveHealth(), DisableHealth(), EnableHealth(), IsHealthDisabled |
world.GetSingleton<Clock>(), HasSingleton, GetOrAddSingleton, RemoveSingleton | world.Clock, HasClock, GetOrAddClock(), RemoveClock() |
world.Index<Zone, int>(), world.Relations<Friend>() | world.ZoneIndex, world.FriendIndex |
item.Component1 | item.Health |
int hpGeneric = player.Get<Health>().Value;int hp = player.Health.Value;EECS034
A system runs a world update. Error. No code fix.
World.Update() and World.Update<TGroup>() run systems. Called from a system, Update() runs the system again
inside its own run until the stack overflows, and a group's update runs other systems in the middle of a stage, under
its change tick. A stable [ForEach] method that calls it is EECS013.
public class CatchUp : EcsSystem
{
protected override void OnUpdate() => World.Update();
}The code that hosts the world runs its updates and groups, in the order they belong:
while (running) world.Update();Related
Last updated on
How is this guide?
Debugging and diagnostics
Debug a running EasyEcs world: tables and memory with Describe, an entity's components in the debugger, per-system timing and the systems that failed.
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.