EasyEcs

Getting started

Build a small ECS simulation in C# step by step, from dotnet new console to components, tags, queries, systems, singletons, system groups and the update loop.

This tutorial builds a small simulation from an empty console project: a thousand units walk east, some of them are on fire, the burning ones die and their corpses are removed, and a report prints once a second. Each step adds one concept, compiles and links to the guide page that covers it in depth. It takes about fifteen minutes.

You need the .NET 10 SDK. EasyEcs targets net10.0 only.

Build it step by step

Create a project

dotnet new console -n Arena
cd Arena
dotnet add package EasyEcs

The package brings the source generator, the analyzer and its code fixes with it. There is nothing to register and no partial to write: everything lives in the EasyEcs namespace.

Other ways to start

  • dotnet new install EasyEcs.Templates, then dotnet new easyecs -n Arena (add --tests for an NUnit project with a test file per system): a fixed-tick server, ready to run, laid out the way this tutorial ends up: Components/, Systems/ with one system per file, and a Program.cs that only hosts the world. Inside the project, dotnet new easyecs-system -n RegenSystem -o Systems adds a system (templates).
  • Complete programs to read, from the smallest up: samples/, starting with HelloWorld.

Define components and tags

A component is a plain struct implementing IComponent: fields, no logic. A struct with no fields is a tag, a yes-or-no state that systems filter on. Create Components.cs:

Components.cs
using EasyEcs;

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;
public record struct Burning(int Ticks) : IComponent;   // a status that comes and goes
public struct Dead : IComponent;                        // a tag: no fields

Components must be structs: a class fails the build with EECS006. Keep them small and split what systems read separately, because a pass loads only the columns it uses.

Create a world and entities

A World holds entities, their components, singletons and systems. Worlds share nothing; a server typically runs one per map or zone. Replace Program.cs with:

Program.cs
using EasyEcs;

using var world = new World();

var units = new Entity[1_000];
world.CreateEntities(units, new Position(0, 0), new Velocity(1, 0), new Health(100));
for (int i = 0; i < units.Length; i += 10) units[i].SetBurning(40);   // every tenth unit is on fire

CreateEntities places a whole wave in its final table at once; world.CreateEntity(a, b, …) creates one entity the same way. An Entity is a handle. Ids are recycled after Destroy(), and the handle's version makes sure an old handle never reaches the entity that reuses its id. More in Entities and components.

Read and write components

For every component the generator writes named members: scout.Velocity is a ref into storage, SetBurning(…) adds or overwrites, HasBurning and RemoveBurning() do what they say. Use these in your code; the generic API underneath (Get<T>(), Read<T>(), Set(…), Has<T>(), Remove<T>()) is for generic code. Add to Program.cs:

Entity scout = units[1];
scout.Velocity = new Velocity(2, 0);         // writes in place, through the ref
float speed = scout.Velocity.X;              // reads through the same ref: 2
scout.SetBurning(5);                         // adds the component
bool burning = scout.HasBurning;             // true
scout.RemoveBurning();                       // removes it: the entity keeps its row

Adding and removing a component are structural changes. They apply at once, anywhere, even in the middle of a system's pass. A ref stays valid until the next structural change and never across await (ref and await).

Query entities

Outside systems (tools, tests, request handlers), ask the world directly. A QueryFilter adds conditions beyond the components:

var alive = QueryFilter.Create().Without<Dead>();       // in real code: a static readonly field
int movers = world.Count<Position, Velocity>(alive);
int onFire = world.Count<Burning>();
Console.WriteLine($"{movers} movers, {onFire} on fire");

float front = 0;
foreach (var item in world.Query<Position>(alive))
    front = MathF.Max(front, item.Position.X);          // items hand out refs; item.Entity is the handle

Queries allocate nothing. More in Queries and filters, including struct jobs, the fastest ad-hoc pass.

Write a system

A system derives from EcsSystem and has one job. A [ForEach] method is its whole loop: it runs once per entity that has its component parameters, ref for what it writes and in for what it reads. Filters are attributes. Create Systems.cs:

Systems.cs
using EasyEcs;

public class MovementSystem : EcsSystem
{
    [ForEach, Without<Dead>]                                  // movers that are not dead
    static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y);
}

public class BurnSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Burn(Entity unit, ref Burning burning, ref Health hp)
    {
        hp.Value -= 3;
        if (--burning.Ticks == 0) unit.RemoveBurning();       // safe in the middle of the pass
    }
}

The generator compiles each method into a struct job that the JIT inlines into the row loop: no delegate, no virtual call per entity. The ref and in keywords also tell the scheduler what the system touches, which is how parallel systems stay safe. More in Systems.

Keep world state in a singleton

Systems keep no state of their own (EECS007). Data with one value per world, such as a clock or a score, is a singleton: a struct implementing ISingletonComponent. Add it to Components.cs:

Components.cs
public record struct Arena(long Tick, int Deaths) : ISingletonComponent;

A [ForEach] method takes a singleton as a parameter, resolved once per pass. Code outside a [ForEach] reaches it as World.Arena (generated) or World.GetSingleton<Arena>(). Add to Systems.cs:

Systems.cs
public class ClockSystem : EcsSystem
{
    protected override void OnUpdate() => World.Arena.Tick++;
}

More in Singletons.

React to state and order systems

Systems never call each other (EECS008); they cooperate through data. The death system writes a state, the Dead tag, and the corpse system reacts to it without the death system knowing it exists. [UpdateAfter<T>] orders them by data flow. Add to Systems.cs:

Systems.cs
[UpdateAfter<BurnSystem>]                                     // after the damage is dealt
public class DeathSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Die(Entity unit, in Health hp, ref Arena arena)
    {
        if (hp.Value > 0) return;
        unit.SetDead();                                       // a state change is data
        arena.Deaths++;
    }
}

[UpdateAfter<DeathSystem>]
public class CorpseSystem : EcsSystem
{
    protected override void OnUpdate() => World.DestroyEntities<Dead>();   // every corpse in one pass
}

The tag applies at once: the corpse system sees it in the same update, and [Without<Dead>] keeps every other system away from the dead. Why this design scales is in ECS principles.

Run the update loop

Add the singleton and the systems, then call world.Update() on a fixed tick. Add to the end of Program.cs:

world.AddSingleton<Arena>();
world.AddSystem<MovementSystem>();
world.AddSystem<BurnSystem>();
world.AddSystem<DeathSystem>();
world.AddSystem<CorpseSystem>();
world.AddSystem<ClockSystem>();

using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(50));   // 20 ticks per second
for (int tick = 1; tick <= 100; tick++)
{
    await timer.WaitForNextTickAsync();
    world.Update();                                                    // every system, synchronously
}

Console.WriteLine($"{world.Arena.Deaths} dead, the scout is at {scout.Position.X}");

Update() runs every enabled system once, in registration order adjusted by [UpdateBefore<T>] / [UpdateAfter<T>], and allocates nothing. A system can run less often by overriding UpdateInterval, or be switched off with Enabled = false.

Add a second cadence with a system group

Not everything runs every tick. A system group is a struct implementing ISystemGroup; systems marked [UpdateInGroup<G>] run only when you call world.Update<G>(). Add a report that prints once a second:

Components.cs
public struct Report : ISystemGroup;
Systems.cs
[UpdateInGroup<Report>]
public class ReportSystem : EcsSystem
{
    protected override void OnUpdate() =>
        Console.WriteLine($"tick {World.Arena.Tick}: {World.EntityCount} units, " +
                          $"{World.Count<Burning>()} burning, {World.Arena.Deaths} dead");
}

Register it with the others (world.AddSystem<ReportSystem>();) and call its group every twentieth tick:

world.AddSystem<ReportSystem>();
for (int tick = 1; tick <= 100; tick++)
{
    world.Update();
    if (tick % 20 == 0) world.Update<Report>();                        // once a second at 20 Hz
}

On a real server, one group handles input whenever it arrives and another runs the simulation on its fixed tick.

Run it

dotnet run

With the whole program below, it prints:

1000 movers, 100 on fire
tick 20: 1000 units, 100 burning, 0 dead
tick 40: 900 units, 0 burning, 100 dead
tick 60: 900 units, 0 burning, 100 dead
tick 80: 900 units, 0 burning, 100 dead
tick 100: 900 units, 0 burning, 100 dead
the scout is at 200, the others at 100

The hundred burning units lose 3 health per tick and die on the 34th tick; their corpses are destroyed in the same update. The scout moves twice as fast as the others.

The whole program

Where to go next

The simulation uses the core of EasyEcs. Each of these adds one capability to it:

ToRead
Lay the program out as a real project: folders, one system per file, testsStructuring a real project
Design features as data plus one-job systemsECS principles
Send clients only what changed, or went awayChange tracking
Spawn kinds of units from a recipePrefabs
Find a player by name, the items of an ownerIndexes and relations
Give each unit a list (a bag, a path)Dynamic buffers
Use every coreThreading
Save the world and load it after a restartSaves
Run the world in ASP.NET Core or a Worker ServiceHosting in a .NET server
Test each system and the whole tickTesting systems
See every API on one pageCheat sheet
Edit on GitHub

Last updated on

How is this guide?

On this page