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;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| Call | Effect |
|---|---|
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 T | Replaces it: enabled, with the new value |
Remove<T>() on a disabled T | Drops 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 everythingWhy 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.ECS | DefaultEcs | EasyEcs | |
|---|---|---|---|
| How | entity.Enabled = false: a hidden tag, queries skip it unless WithDisabled() | entity.Disable(): the entity leaves every entity set | A tag of yours and Without<T> |
| Switching off or on | Moves the row to another archetype | Updates every set | Flips a presence bit (after the first time) |
| Iterating past disabled entities | Skips their archetype | They are in no set | Free 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
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 | Tag | 42.4 μs | 1.00× | 0 B |
| EasyEcs | DisableComponent | 41.4 μs | 0.98× | 0 B |
| Friflo.Engine.ECS | Enabled | 45.9 μs | 1.08× | 0 B |
| Arch | Tag | 82.8 μs | 1.95× | 0 B |
| DefaultEcs | Disable | 103 μs | 2.42× | 0 B |
100,000 units, 10,000 fall asleep and wake per operation
- EasyEcs
- Other libraries
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 | Tag | 478 μs | 1.00× | 0 B |
| EasyEcs | DisableComponent | 563 μs | 1.18× | 0 B |
| Friflo.Engine.ECS | Enabled | 797 μs | 1.67× | 0 B |
| Arch | Tag | 1.26 ms | 2.63× | 0 B |
| DefaultEcs | Disable | 745 μs | 1.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 1The 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 of | Do | Why |
|---|---|---|
| Releasing a resource in every place that destroys | A cleanup component and one system | One release path, also for bulk destroys and cascades |
| Removing and re-adding a component to pause it | Disable<T>() / Enable<T>() | The value stays; Set would need it stored elsewhere |
A loop of Disable over many entities | world.DisableAll<T>(filter) | 64 rows at a time, one word of presence bits (bulk) |
| A flag field every system tests | A 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):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| Cleanup | 102 μs | 1.00× | 0 B |
| Plain | 43.9 μs | 0.43× | 0 B |
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| DisableAndEnable | 22.9 μs | 0.26× | 0 B |
| DisableAndEnableEach | 2.27 ms | 26× | 0 B |
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 theDisabled<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
Inactiverow skip the test. Spawned: a tag like any other: a bit flip to add, a bit flip to remove.
Pitfalls
| Mistake | What happens | Caught by |
|---|---|---|
A cleanup system without With<Destroyed> | It releases resources of live entities | Code review |
| Never removing the last cleanup component | The retired entity stays forever | world.Count<Destroyed>() in your stats |
Disable<T>() on a cleanup component or ChildOf | InvalidOperationException | At run time |
Set on a disabled component expecting it to stay disabled | Set enables it with the new value; use Enable to get the kept value back | By design |
Forgetting Without<Inactive> on a system | Pooled entities keep moving | Code review |
Expecting [Changed<T>] to tell new from written | Both are writes | Use a Spawned tag |
Related
Last updated on
How is this guide?
Bulk changes
Set, remove, disable or enable one component on every entity a filter selects in one pass, for round resets, zone-wide statuses and waves, with 0 B allocated.
ref and await
Change components through a ref. Which refs survive a structural change, why none may cross an await, and how async code reaches the world safely.