EasyEcs

Singletons

World-level state in EasyEcs: one struct value per world for the clock, configuration, counters or a grid, with [ForEach] parameters and SingletonRef handles.

Some state belongs to the whole world, not to an entity: the tick clock, the match configuration, a score, a spatial grid. A singleton is a struct that implements ISingletonComponent, with exactly one value per world. It is where world-level state goes, since systems keep none (EECS007), and because it lives in the world, two worlds on two threads never share it.

When to use it

Use it for

World-level state that systems read or write: the clock and delta time, configuration loaded at startup, counters and totals, a spatial grid or a lookup table, the queue of input a system drains each tick.

Skip it for

Static fields: every world in the process would share them. Per-entity data: that is a component. A list of things that each have their own state (players in a match): those are entities with a tag, which queries and indexes can select.

How to use it

Declare it

public record struct Clock(long Tick, float DeltaTime) : ISingletonComponent;
public record struct Score(int Deaths) : ISingletonComponent;

Add, read and write

var world = new World();
world.SetClock(0, 1f / 30);                              // generated: adds it, or overwrites it
world.Clock.Tick++;                                       // generated: a ref, throws if not added
ref var score = ref world.GetOrAddScore();                // adds a default value if missing
score.Deaths++;

Take it in a system

A [ForEach] method takes a singleton as a ref or in parameter. It is resolved once per pass, not once per entity. The singleton must exist by then: a system whose singleton was never added throws InvalidOperationException on its first run, even when no entity matches, so add it where the world is built.

public class DeathSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Die(Entity unit, in Health hp, ref Score score)
    {
        if (hp.Value > 0) return;
        unit.SetDead();
        score.Deaths++;
    }
}

public class ClockSystem : EcsSystem
{
    protected override void OnUpdate() => World.Clock.Tick++;   // in OnUpdate: through the system's World
}

The API

CallGenerated memberEffect
ref T AddSingleton<T>()Adds it, or resets an existing one to default in place
ref T GetSingleton<T>()world.ClockA ref; throws if it was not added
ref T GetOrAddSingleton<T>()world.GetOrAddClock()A ref, adding default first if missing
GetOrAddSingleton<T>() = valueworld.SetClock(tick, deltaTime)Sets the value, adding it if missing
bool HasSingleton<T>()world.HasClockWhether it exists
bool TryGetSingleton<T>(out T)A copy, if present
bool RemoveSingleton<T>()world.RemoveClock()Removes it; false if it was not added
SingletonRef<T> SingletonRef<T>()A stable handle; throws if it was not added
world.SetScore(0);                                        // generated from the record's constructor
bool has = world.HasClock;
if (world.TryGetSingleton<Clock>(out var copy)) Console.WriteLine(copy.Tick);
world.RemoveScore();

The generated members follow the rules of generated members: SetX has one overload per public constructor, and a singleton without fields gets no GetOrAddX.

Stable handles

A singleton's storage never moves, unlike component rows. world.SingletonRef<T>() returns a SingletonRef<T> (it throws if the singleton was not added) whose Value is a ref T with no lookup at all, valid for as long as the singleton exists. Take it once at setup and keep it, in a field of your host or a local of a loop.

var clock = world.SingletonRef<Clock>();     // once, at setup
clock.Value.Tick++;                          // later: a ref, no lookup
  • AddSingleton<T>() on an existing singleton resets it in place, so the handle sees the reset value.
  • RemoveSingleton<T>() detaches it: writes through the old handle no longer reach the world, also after the singleton is added again. Take a new handle then.
  • Snapshots restore singletons into the same storage, so handles keep working after a Restore.
  • Generated [ForEach] jobs resolve each singleton parameter once per pass; parallel jobs, which are copied to other threads, carry a SingletonRef<T>.

Singletons and threads

  • A singleton belongs to its world, so one world per thread shares nothing.
  • With WorldOptions.ParallelSystems, a system that takes a singleton by ref writes it: it never shares a stage with another system that reads or writes the same singleton. Take it by in when the system only reads it.
  • A [ForEach(Parallel = true)] method takes singletons only by in: every chunk would race on a ref (EECS010).
  • A singleton that holds a collection (a grid of cells, a queue) and is changed through an in parameter is scheduled as a read: EECS011 asks for ref.

Full example

A clock, a configuration and a score as singletons: poison hurts three units each tick, and the death system counts the dead. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

  tick 2: Entity 0v1 dies
after tick 2: 1 dead
  tick 3: Entity 2v1 dies
  tick 3: Entity 1v1 dies
after tick 3: 3 dead

The host reads the score through the SingletonRef<Score> it took once, and the systems see the configuration it changes on the next update: with the poison doubled, both remaining units die on tick 3.

How to use it fast

Instead ofDoWhy
GetSingleton<T>() (or World.X) per entity inside a loopA singleton parameter of the [ForEach] methodResolved once per pass (EECS027 in a [ForEach] method)
A lookup on every call from host codeA SingletonRef<T> kept from setupNo lookup
ref for a singleton the system only readsinLets the system share a parallel stage (EECS025)
A static fieldA singletonPer world, saved and snapshotted with it

1,000 singleton reads and writes through GetSingleton<T>(), next to 1,000 component writes through entity handles (MicroBenchmarks):

CaseMeanvs baselineAllocated
SingletonAccess1.01 μs0.08×0 B
HandleAccess3.33 μs0.26×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

A pass that writes a singleton for each of 100,000 entities, against Friflo.Engine.ECS:

A pass that writes a singleton, 100,000 entities

  • EasyEcs
  • Friflo.Engine.ECS
SingletonFriflo.Engine.ECS 1.05×212 μs · 0 B222 μs · 0 B0.00 ns50.0 μs100 μs150 μs200 μsTime (shorter is faster)

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Data table
LibraryCaseMeanvs EasyEcsAllocated
EasyEcsSingleton212 μs1.00×0 B
Friflo.Engine.ECSSingleton222 μs1.05×0 B

What it costs

  • Storage: one small box per singleton type in each world that has it; nothing per entity.
  • GetSingleton, HasSingleton: a bounds check, one array load and a null check, with no type check; O(1).
  • SingletonRef<T>.Value: one field load.
  • A [ForEach] parameter: resolved once per pass.
  • Adding or removing a singleton goes through the world's structural gate, like any structural change.

Pitfalls

MistakeWhat happensCaught by
State kept in a system field insteadInvisible to other systems, lost on remove, shared by worlds if staticEECS007
A class implementing ISingletonComponentDoes not compileEECS006
Reading a singleton before it was added (world.X, GetSingleton<T>(), a [ForEach] parameter)InvalidOperationException, naming the call that adds itAdd it at setup, or use GetOrAddX() where the default is right
A ref singleton in a parallel methodRaces between chunksEECS010
AddSingleton or RemoveSingleton in a batch method, a parallel method or a parallel stageInvalidOperationException: both go through the structural gate, and the structure is frozen thereEECS010, EECS013, and at run time
Changing a collection in a singleton through inScheduled as a readEECS011
Writing through a SingletonRef<T> after RemoveSingletonThe write reaches nothingTake a new handle after re-adding
A list of players in a singletonDuplicates what entities and queries giveMake them entities with a tag
Edit on GitHub

Last updated on

How is this guide?

On this page