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
| Call | Generated member | Effect |
|---|---|---|
ref T AddSingleton<T>() | Adds it, or resets an existing one to default in place | |
ref T GetSingleton<T>() | world.Clock | A ref; throws if it was not added |
ref T GetOrAddSingleton<T>() | world.GetOrAddClock() | A ref, adding default first if missing |
GetOrAddSingleton<T>() = value | world.SetClock(tick, deltaTime) | Sets the value, adding it if missing |
bool HasSingleton<T>() | world.HasClock | Whether 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 lookupAddSingleton<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 aSingletonRef<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 byrefwrites it: it never shares a stage with another system that reads or writes the same singleton. Take it byinwhen the system only reads it. - A
[ForEach(Parallel = true)]method takes singletons only byin: every chunk would race on aref(EECS010). - A singleton that holds a collection (a grid of cells, a queue) and is changed through an
inparameter is scheduled as a read: EECS011 asks forref.
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 deadThe 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 of | Do | Why |
|---|---|---|
GetSingleton<T>() (or World.X) per entity inside a loop | A singleton parameter of the [ForEach] method | Resolved once per pass (EECS027 in a [ForEach] method) |
| A lookup on every call from host code | A SingletonRef<T> kept from setup | No lookup |
ref for a singleton the system only reads | in | Lets the system share a parallel stage (EECS025) |
| A static field | A singleton | Per 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):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| SingletonAccess | 1.01 μs | 0.08× | 0 B |
| HandleAccess | 3.33 μs | 0.26× | 0 B |
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
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
Data table
| Library | Case | Mean | vs EasyEcs | Allocated |
|---|---|---|---|---|
| EasyEcs | Singleton | 212 μs | 1.00× | 0 B |
| Friflo.Engine.ECS | Singleton | 222 μs | 1.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
| Mistake | What happens | Caught by |
|---|---|---|
| State kept in a system field instead | Invisible to other systems, lost on remove, shared by worlds if static | EECS007 |
A class implementing ISingletonComponent | Does not compile | EECS006 |
Reading a singleton before it was added (world.X, GetSingleton<T>(), a [ForEach] parameter) | InvalidOperationException, naming the call that adds it | Add it at setup, or use GetOrAddX() where the default is right |
A ref singleton in a parallel method | Races between chunks | EECS010 |
AddSingleton or RemoveSingleton in a batch method, a parallel method or a parallel stage | InvalidOperationException: both go through the structural gate, and the structure is frozen there | EECS010, EECS013, and at run time |
Changing a collection in a singleton through in | Scheduled as a read | EECS011 |
Writing through a SingletonRef<T> after RemoveSingleton | The write reaches nothing | Take a new handle after re-adding |
| A list of players in a singleton | Duplicates what entities and queries give | Make them entities with a tag |
Related
Last updated on
How is this guide?
Systems and [ForEach]
Write per-tick logic as stateless systems with [ForEach] methods: parameters, filters, ordering, groups, batch and parallel methods, runners and errors.
Structural changes
Create, destroy, add and remove components in the middle of a pass. EasyEcs applies them at once, with no command buffer, visiting each entity at most once.