EasyEcs

Cleanup and disable

Release outside resources exactly once with ICleanupComponent, pause a component with Disable<T> and switch whole entities off in a C# ECS.

Four lifecycle needs of a server, each solved with data. A session that holds a socket must close it once, even when the session is destroyed in a bulk call: a cleanup component keeps the entity until a system releases it. A cooldown paused by a stun must keep its value: Disable<T>() hides a component and keeps it. A pooled bullet must leave every system without being destroyed: a tag with Without<T> switches the whole entity off. And a system that greets new players needs to tell them apart: a Spawned tag marks them.

When to use it

Use it for

Cleanup components: anything outside the world released exactly once (sockets, seats, leases, file handles, a slot in another service). Disable<T>(): a component paused for a while with its value kept (a cooldown under a stun, an AI behaviour while a cutscene runs). A tag: whole entities parked (pools, sleeping zones, players reconnecting).

Skip it for

Cleanup components for state the world owns: destroying the entity already frees it. Disable<T>() for a state you can express as a tag the systems read: a tag is clearer. Whole-entity disable "by default" does not exist on purpose: see Disabling a whole entity.

How to use it

Cleanup components

An entity destroyed while it holds an ICleanupComponent is not freed. It loses every other component, gets the Destroyed tag, and stays alive until its last cleanup component is removed:

public record struct Seat(int Number) : ICleanupComponent;   // a resource outside the world
public record struct Seats(int Released) : ISingletonComponent;
ReleaseSeats.cs
public class ReleaseSeats : EcsSystem
{
    [ForEach, With<Destroyed>, With<Seat>]                    // only entities already destroyed
    static void Release(Entity entity, ref Seats seats)
    {
        seats.Released++;                                     // give the seat back here
        entity.RemoveSeat();                                  // the last cleanup component: the entity is freed
    }
}
world.AddSingleton<Seats>();
world.AddSystem<ReleaseSeats>();
var guest = world.CreateEntity(new Seat(7), new Health(10));

guest.Destroy();                       // alive, tagged Destroyed, Health gone
world.Update();                        // ReleaseSeats frees it: guest.IsAlive is false
  • Every destroy path retires such entities: Destroy, DestroyEntities<T>(), a hierarchy cascade or a target policy.
  • A system that acquires the resource filters Without<Destroyed>: a retired entity still holds its cleanup component, so without the filter it could acquire again after it left:
public record struct NextSeat(int Number) : ISingletonComponent;

public class AssignSeats : EcsSystem
{
    [ForEach, Without<Destroyed>]                            // never seat an entity that already left
    static void Assign(ref Seat seat, ref NextSeat next)
    {
        if (seat.Number != 0) return;                        // already seated
        next.Number++;
        seat = new Seat(next.Number);                        // take the seat here
    }
}
  • Destroying a retired entity again does nothing. Removing a cleanup component from a live entity just removes it.
  • A retired entity leaves its indexes, and its children go with it.
  • A cleanup component cannot be disabled (Disable<T>() throws): it must stay to be released.

Disabling a component

Disable<T>() keeps the value of T but hides it: queries, Has and Get act as if the entity lacked T, until Enable<T>() gives it back. The entity gets the tag Disabled<T>, which you can query.

public record struct Cooldown(int Ticks) : IComponent;

public class TickCooldowns : EcsSystem
{
    [ForEach]
    static void Tick(ref Cooldown cooldown) => cooldown.Ticks--;
}
world.AddSystem<TickCooldowns>();
var caster = world.CreateEntity(new Cooldown(3));

caster.DisableCooldown();               // stunned: the cooldown is paused, its value kept
world.Update();                         // TickCooldowns skips it
bool paused = caster.IsCooldownDisabled;
int stunnedCasters = world.Count<Disabled<Cooldown>>();

caster.EnableCooldown();                // back with Ticks = 3
CallEffect
DisableX() (generated) / Disable<T>()Hides T, keeps its value, adds Disabled<T>. False if the entity lacks T
EnableX() (generated) / Enable<T>()Gives the kept value back. False if T is not disabled
IsXDisabled (generated) / IsDisabled<T>()Whether the entity has Disabled<T>
Set(new T(...)) on a disabled TReplaces it: enabled, with the new value
Remove<T>() on a disabled TDrops it: nothing left to enable
world.DisableAll<T>(filter) / EnableAll<T>(filter)The same on every match, in bulk

A disable counts as a removal for [Removed<T>], and an enable as a write for [Changed<T>], so replication sees both. An indexed component leaves its index while disabled. The kept value survives moves, clones, snapshots and saves.

Disabling a whole entity

There is no "disabled entity" that queries skip by default. A tag and Without<T> do it, and say so where it matters:

public struct Inactive : IComponent;                         // the whole entity is off
public struct Bullet : IComponent;

public class MoveBullets : EcsSystem
{
    [ForEach, Without<Inactive>]                             // the systems that skip it say so
    static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y);
}
var bullet = world.CreateEntity(new Position(0, 0), new Velocity(1, 0), new Bullet());
bullet.SetInactive();                                        // back to the pool: after the first time, a bit flip
bullet.SetPosition(5, 5).RemoveInactive();                   // reused
int pooled = world.Count<Bullet>(QueryFilter.Create().With<Inactive>());   // saves, cleanup and stats see everything

Why a tag (decision D8): excluding by default would make every query depend on a state it does not name. A save, a cleanup or a count that must see every entity would have to opt back in, and forgetting it fails silently. The tag is data the generator and the reader both see.

Friflo.Engine.ECSDefaultEcsEasyEcs
Howentity.Enabled = false: a hidden tag, queries skip it unless WithDisabled()entity.Disable(): the entity leaves every entity setA tag of yours and Without<T>
Switching off or onMoves the row to another archetypeUpdates every setFlips a presence bit (after the first time)
Iterating past disabled entitiesSkips their archetypeThey are in no setFree while a table has none; a test per 64 rows when mixed

The measured cost, with 100 units switching per operation (most stay as they are) and with 10,000 (frequent switching), then the awake units summed (DisableComparison):

100,000 units, 100 fall asleep and wake per operation

  • EasyEcs
  • Other libraries
EasyEcs: Tag0 B allocated42.4 μsEasyEcs: DisableComponent0.98× · 0 B allocated41.4 μsFriflo.Engine.ECS: Enabled1.08× · 0 B allocated45.9 μsArch: Tag1.95× · 0 B allocated82.8 μsDefaultEcs: Disable2.42× · 0 B allocated103 μs0.00 ns20.0 μs40.0 μs60.0 μs80.0 μs100 μ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
EasyEcsTag42.4 μs1.00×0 B
EasyEcsDisableComponent41.4 μs0.98×0 B
Friflo.Engine.ECSEnabled45.9 μs1.08×0 B
ArchTag82.8 μs1.95×0 B
DefaultEcsDisable103 μs2.42×0 B

100,000 units, 10,000 fall asleep and wake per operation

  • EasyEcs
  • Other libraries
EasyEcs: Tag0 B allocated478 μsEasyEcs: DisableComponent1.18× · 0 B allocated563 μsFriflo.Engine.ECS: Enabled1.67× · 0 B allocated797 μsArch: Tag2.63× · 0 B allocated1.26 msDefaultEcs: Disable1.56× · 0 B allocated745 μs0.00 ns200 μs400 μs600 μs800 μs1.00 ms1.20 msTime (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
EasyEcsTag478 μs1.00×0 B
EasyEcsDisableComponent563 μs1.18×0 B
Friflo.Engine.ECSEnabled797 μs1.67×0 B
ArchTag1.26 ms2.63×0 B
DefaultEcsDisable745 μs1.56×0 B

Pools and effects switch often, where a bit flip beats a row move. When many entities stay off for long, mixed with awake ones in one table, GroupBy on a sleeping state puts them in tables of their own.

Telling new entities apart: the Spawned tag

There is no Added<T> filter. [Changed<T>] already selects rows that gained T (adding stamps the tick, as a write does). When a system must tell a new entity from a written one, the creator adds a tag and the reacting system removes it (decision D4):

public struct Spawned : IComponent;
public record struct Greeted(int Count) : ISingletonComponent;

public class GreetNewcomers : EcsSystem
{
    [ForEach, With<Spawned>, With<Health>]
    static void Greet(Entity entity, ref Greeted greeted)
    {
        greeted.Count++;                                     // first-time work
        entity.RemoveSpawned();                              // a bit flip: greeted once
    }
}
world.AddSingleton<Greeted>();
world.AddSystem<GreetNewcomers>();
world.CreateEntity(new Health(100), new Spawned());          // the creator says it is new
world.Update();

The tag is explicit, queryable, saved with the world and costs one presence bit flip.

Full example

A player holds a seat at a table, a resource outside the world, and a cooldown that is paused while it is stunned. When the player leaves, a system gives the seat back before the entity is freed. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

stunned: has cooldown False, stunned players 1
resumed: 2 ticks left
destroyed: alive True, tagged True
after the update: alive False, seats released 1

The cooldown went from 3 to 2: the update during the stun skipped it. Between Destroy and the next update the player is still alive, but only ReleaseSeatsSystem sees it, because it asks for Destroyed.

How to use it fast

Instead ofDoWhy
Releasing a resource in every place that destroysA cleanup component and one systemOne release path, also for bulk destroys and cascades
Removing and re-adding a component to pause itDisable<T>() / Enable<T>()The value stays; Set would need it stored elsewhere
A loop of Disable over many entitiesworld.DisableAll<T>(filter)64 rows at a time, one word of presence bits (bulk)
A flag field every system testsA tag and Without<T>Tables without the tag skip the test entirely

10,000 sessions with an outside resource, 1,000 disconnecting and 1,000 connecting per operation, with a cleanup component against a plain component released before the destroy (CleanupBenchmark); and 100,000 entities disabled and enabled in bulk and one by one (BulkBenchmark):

CaseMeanvs baselineAllocated
Cleanup102 μs1.00×0 B
Plain43.9 μs0.43×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
CaseMeanvs baselineAllocated
DisableAndEnable22.9 μs0.26×0 B
DisableAndEnableEach2.27 ms26×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

What it costs

  • Cleanup components: a retired entity keeps its id and a row with its cleanup components until released; a world without them pays nothing on destroy.
  • Disable<T>(): O(1). The first disable in a table moves the row once, to the table with the Disabled<T> column; after that a disable or enable flips presence bits.
  • A tag: one presence bit per row; a flip after the first time. Tables with no Inactive row skip the test.
  • Spawned: a tag like any other: a bit flip to add, a bit flip to remove.

Pitfalls

MistakeWhat happensCaught by
A cleanup system without With<Destroyed>It releases resources of live entitiesCode review
Never removing the last cleanup componentThe retired entity stays foreverworld.Count<Destroyed>() in your stats
Disable<T>() on a cleanup component or ChildOfInvalidOperationExceptionAt run time
Set on a disabled component expecting it to stay disabledSet enables it with the new value; use Enable to get the kept value backBy design
Forgetting Without<Inactive> on a systemPooled entities keep movingCode review
Expecting [Changed<T>] to tell new from writtenBoth are writesUse a Spawned tag
Edit on GitHub

Last updated on

How is this guide?

On this page