Class World
Namespace: KenseiECS
World — ECS entry point. Owns entity lifecycle, component pools, and filter registry.
Filters are updated reactively: when a component is added or removed, World checks all filters that depend on that component type and adds/removes the entity as needed.
Not thread-safe. All access to a World, its pools and filters must happen on one thread (or be externally synchronized).
public class WorldInheritance
Inherited Members
object.Equals(object?), object.Equals(object?, object?), object.GetHashCode(), object.GetType(), object.MemberwiseClone(), object.ReferenceEquals(object?, object?), object.ToString()
Extension Methods
WorldEventBufferExtensions.AddEvent<T>(World, Entity, T), WorldListenerExtensions.CreateWithListener<T>(World, T), WorldListenerExtensions.HasListeners<T>(World, Entity), WorldListenerExtensions.Subscribe<T>(World, Entity, T), WorldListenerExtensions.Unsubscribe<T>(World, Entity, T), WorldListenerExtensions.UnsubscribeLater<T>(World, Entity, T)
Constructors
World()
Create a world with Default() settings.
public World()World(WorldConfig)
Create a world with the given capacities. Non-positive values fall back to Default().
public World(WorldConfig config)Parameters
config WorldConfig
Fields
Id
Unique world ID.
public readonly int IdField Value
Properties
ActivePools
Enumerate all registered (non-null) component pools. Zero-allocation.
public World.ActivePoolEnumerable ActivePools { get; }Property Value
AliveEntities
Enumerate all alive entities. Zero-allocation.
public World.AliveEntityEnumerable AliveEntities { get; }Property Value
ChangeVersion
Current change version. Capture it at the end of a system's Run and pass it to pool.ChangedSince next time to see only components modified since then.
public int ChangeVersion { get; }Property Value
Remarks
The counter advances with every Add, Modify and MarkChanged on a tracking pool. After int.MaxValue of them it starts again at 1, and ChangedSince keeps working across that: compare versions with it, not with >. Once the counter has started again, a bookmark is exact for the next 2^30 (about a billion) such writes; against an older one a component written before it can be reported as changed, and a bookmark older than int.MaxValue writes means nothing. 0, the value of a world that tracked no write yet, always stands for "everything changed since".
EntityCount
Number of currently alive entities.
public int EntityCount { get; }Property Value
FilterCount
Number of registered filters.
public int FilterCount { get; }Property Value
FirstGrowthAfterReserve
The first growth counted by GrowthsAfterReserve: which array of which pool, filter or world outgrew its reserve, its sizes and the tick — the place to look when the count is not 0, without recording the world in EcsProfiler. Later growths do not replace it, and Clear() resets neither it nor the count. Recording it allocates nothing beyond the owner's name (a pool's type name or a filter's description, built once per pool or filter). Empty (IsEmpty) while nothing outgrew a reserve, and always unless KenseiECS is compiled with KENSEI_DEBUG.
public StorageGrowth FirstGrowthAfterReserve { get; }Property Value
GroupCount
Number of registered owning groups.
public int GroupCount { get; }Property Value
GrowthsAfterReserve
Number of times a storage array grew past the size a reserve stated for it: the world's entity slots or free-slot list past ReservedEntities; a reserved pool's dense arrays past its ReservedComponents and its sparse array past ReservedEntities (once entity slots were reserved); a reserved filter's dense array past its ReservedCount and its sparse pages past ReservedEntities; with the obsolete Reserve(), every pool and filter in the dimensions it was given. A pool or filter that nothing reserved grows on demand and is not counted. Non-zero means a reserve is too small for the peak, and that frame allocated. Always 0 unless KenseiECS is compiled with KENSEI_DEBUG.
public int GrowthsAfterReserve { get; }Property Value
IsDestroyed
True after Destroy() has been called.
public bool IsDestroyed { get; }Property Value
ReservedEntities
Entity slots reserved so far: the highest value passed to ReserveEntities() (or to the obsolete Reserve()), 0 while nothing was reserved. The world's per-entity arrays and the sparse side of every reserved pool and filter cover this many slots.
public int ReservedEntities { get; }Property Value
Tick
Current tick number. Starts at 0, incremented by NextTick(). First run = tick 1.
public int Tick { get; }Property Value
Methods
Add<T>(Entity, T)
Add a component to an entity. Throws if the entity already has it.
public ref T Add<T>(Entity entity, T component) where T : struct, IComponentParameters
entity Entity
component T
Returns
T
Type Parameters
T
AddEventListener(IWorldEventListener)
Register a world event listener.
public void AddEventListener(IWorldEventListener listener)Parameters
listener IWorldEventListener
Clear()
Reset the world to a clean state. All entities destroyed, all pools and filters emptied. Pools, filters, and their registrations are preserved — only data is cleared. No reallocation needed on next use. Does not fire world events. Called by a listener, it ends what is still running about the entities it removes: a CreateEntity or CopyEntity in progress announces nothing and copies nothing more, a DestroyEntity stops, and the world listeners not told yet of a change in progress are not told of it (Load() does the same).
public void Clear()Exceptions
When the world was destroyed.
CopyEntity(Entity)
Copy an entity — creates a new entity with copies of all components. Returns the new entity. OnEntityCreated fires after all components are copied. If a listener of a copied component destroys the copy, copying stops, OnEntityCreated does not fire and the returned handle is dead (the slot may already hold an entity the listener created). If a listener destroys the source, copying stops there and the copy keeps what it got. A source with no components left (inside the removal of its last component: an IWorldEventListener.OnComponentRemoved or an IFilterListener.OnEntityRemoved of it, which runs before the auto-destroy) is not copied: CopyEntity returns Entity.Null and creates nothing, in every build. If an AutoCopy or a listener of a copied component throws, the copy is destroyed (world listeners hear nothing of it) and the exception is rethrown.
public Entity CopyEntity(Entity source)Parameters
source Entity
Returns
CreateEntity<T>(T)
Create an entity with one initial component. OnEntityCreated fires after the component is added, so listeners never observe an entity without components. If a listener of the component destroys the entity, OnEntityCreated does not fire and the returned handle is dead; neither does OnEntityDestroyed for it, which would tell world listeners of an entity they never heard of.
public Entity CreateEntity<T>(T component) where T : struct, IComponentParameters
component T
Returns
Type Parameters
T
Destroy()
Fully destroy the world. Nulls all internal references so GC can collect. World instance should not be used after this call. Calling it again is a no-op; Clear(), ReserveEntities(), every Reserve and filter creation throw ObjectDisposedException, and so do CreateEntity and Pool under KENSEI_DEBUG. In release CreateEntity and Pool are not checked: NullReferenceException on Mono and .NET, and on IL2CPP, where World has no null checks, a crash of the player. If an AutoReset throws while the components are cleared, the world is destroyed all the same (IsDestroyed is true, a second call is a no-op), then the first such exception is rethrown.
public void Destroy()DestroyEntity(Entity)
Destroy an entity. O(number of component types on the entity). Removes all components and returns the slot to the free list; the slot's generation changes when it is reused. Also called automatically when the last component is removed. Listeners of a component removed here see the components not removed yet (Has, Get). A listener that calls Clear() ends the destroy: Clear has already removed everything and released the slot. If a listener or AutoReset throws, the slot is still released, but components not yet removed stay orphaned in their pools; the slot leaves every filter and group and is not reused until Clear(), which removes the orphans.
public void DestroyEntity(Entity entity)Parameters
entity Entity
Filter()
Start building a new filter. Build filters in Init, not per frame.
public FilterBuilder Filter()Returns
Filter<TSpec>()
Filter from a static spec: world.Filter<Inc<Position, Velocity>>().
public Filter Filter<TSpec>() where TSpec : struct, IFilterSpecReturns
Type Parameters
TSpec
Filter<TSpec1, TSpec2>()
Filter from two static specs: world.Filter<Inc<Position>, Exc<Frozen>>().
public Filter Filter<TSpec1, TSpec2>() where TSpec1 : struct, IFilterSpec where TSpec2 : struct, IFilterSpecReturns
Type Parameters
TSpec1
TSpec2
Filter<TSpec1, TSpec2, TSpec3>()
Filter from three static specs: world.Filter<Inc<A>, Exc<B>, Any<C, D>>().
public Filter Filter<TSpec1, TSpec2, TSpec3>() where TSpec1 : struct, IFilterSpec where TSpec2 : struct, IFilterSpec where TSpec3 : struct, IFilterSpecReturns
Type Parameters
TSpec1
TSpec2
TSpec3
Get<T>(Entity)
Get a component by ref. The ref is valid until the next Add or Remove of the same component type on any entity (Add may grow the pool, Remove swaps another component into the freed slot). When the type belongs to an owning group, an Add or Remove of any of the group's types invalidates it too. Changes to other component types do not affect it.
public ref T Get<T>(Entity entity) where T : struct, IComponentParameters
entity Entity
Returns
T
Type Parameters
T
GetComponentCount(Entity)
Number of components on the entity. O(1).
public int GetComponentCount(Entity entity)Parameters
entity Entity
Returns
GetComponentTypes(Entity, List<int>)
Append the type indices of all components on the entity to result. Returns the number of components. Resolve names via ComponentType.TypeOf.
public int GetComponentTypes(Entity entity, List<int> result)Parameters
entity Entity
Returns
GetEntity(int)
Get the Entity handle for a slot index. For a dead slot this returns the handle of the entity that last lived there (IsAlive is false for it). An int index from a filter is only valid until the end of the current iteration — once the slot is reused the same int names a different entity.
public Entity GetEntity(int entityIndex)Parameters
entityIndex int
Returns
GetFilter(int)
Registered filter by position, for tooling.
public Filter GetFilter(int index)Parameters
index int
Returns
GetGroup(int)
Registered group by position, for tooling.
public Group GetGroup(int index)Parameters
index int
Returns
GetName(Entity)
Debug name of an entity, or null. Always null unless KENSEI_DEBUG is defined.
public string GetName(Entity entity)Parameters
entity Entity
Returns
GetPool(int)
Untyped pool for a type index, or null if no component of that type was ever added.
public ComponentPoolBase GetPool(int typeIndex)Parameters
typeIndex int
Returns
GetSingleton<T>()
The only component of type T. Throws unless exactly one entity has it.
public ref T GetSingleton<T>() where T : struct, IComponentReturns
T
Type Parameters
T
GetSingletonEntity<T>()
The entity holding the only component of type T. Throws unless exactly one entity has it.
public Entity GetSingletonEntity<T>() where T : struct, IComponentReturns
Type Parameters
T
Group<T1, T2>()
Owning group over two component types. Their pools' dense arrays are kept aligned so members can be iterated through Data1/Data2 without lookups. Each pool can belong to one group only; calling again with the same types returns the existing group.
public Group<T1, T2> Group<T1, T2>() where T1 : struct, IComponent where T2 : struct, IComponentReturns
Group<T1, T2>
Type Parameters
T1
T2
Group<T1, T2, T3>()
Owning group over three component types. Their pools' dense arrays are kept aligned so members can be iterated through Data1..Data3 without lookups. Each pool can belong to one group only; calling again with the same types returns the existing group.
public Group<T1, T2, T3> Group<T1, T2, T3>() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponentReturns
Group<T1, T2, T3>
Type Parameters
T1
T2
T3
Group<T1, T2, T3, T4>()
Owning group over four component types. Their pools' dense arrays are kept aligned so members can be iterated through Data1..Data4 without lookups. Each pool can belong to one group only; calling again with the same types returns the existing group.
public Group<T1, T2, T3, T4> Group<T1, T2, T3, T4>() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponentReturns
Group<T1, T2, T3, T4>
Type Parameters
T1
T2
T3
T4
Has<T>(Entity)
Check if entity has a component. Does not create the pool.
public bool Has<T>(Entity entity) where T : struct, IComponentParameters
entity Entity
Returns
Type Parameters
T
HasSingleton<T>()
True when exactly one entity has a component of type T.
public bool HasSingleton<T>() where T : struct, IComponentReturns
Type Parameters
T
IsAlive(Entity)
Check if entity is alive. O(1).
public bool IsAlive(Entity entity)Parameters
entity Entity
Returns
NextTick()
Advance the tick counter. Call once per frame before systems run. Outside a Run() it also applies the listener removals queued by UnsubscribeLater<T>(), for a world whose systems are not driven by a runner.
public void NextTick()Pool<T>()
Get (or lazily create) a typed component pool.
public ComponentPool<T> Pool<T>() where T : struct, IComponentReturns
Type Parameters
T
Remove<T>(Entity)
Remove a component from an entity. No-op if the entity does not have it; does not create the pool. Auto-destroys the entity if it was the last component.
public void Remove<T>(Entity entity) where T : struct, IComponentParameters
entity Entity
Type Parameters
T
RemoveEventListener(IWorldEventListener)
Unregister a world event listener.
public void RemoveEventListener(IWorldEventListener listener)Parameters
listener IWorldEventListener
Reserve(int, int)
Obsolete: grows the world's storage and every pool and filter, including the ones created later. Entity side: entities entity slots (as ReserveEntities()), and the sparse arrays of every pool and filter cover them. Component side: the dense arrays of every pool and filter hold at least components entries. Never shrinks.
[Obsolete("World.Reserve sizes every pool and filter, singletons and the ones created later included (about 4 bytes x entities and `components` slots per type). Use ReserveEntities(entities) for the world and Pool<T>().Reserve(count) for the types whose count changes during play; filters over reserved types follow. Removed in 3.0.")]
public void Reserve(int entities, int components = 0)Parameters
entities int
Number of entity slots to have room for.
components int
Dense capacity for every pool and filter of this world. 0 leaves the dense arrays as they are.
Remarks
Every pool pays: about 4 bytes × entities and components slots of its type, singletons and rarely used types included, and so does every pool and filter created later (1000 types at 50,000 entities: about 200 MB of pool sparse arrays). Use [`ReserveEntities()`](KenseiECS.World.md#KenseiECS_World_ReserveEntities_System_Int32_) for the world and [`Reserve()`](KenseiECS.ComponentPoolBase.md#KenseiECS_ComponentPoolBase_Reserve_System_Int32_) for the types whose count changes during play; filters over reserved types follow.
It does not reserve the pools ([`ReservedComponents`](KenseiECS.ComponentPoolBase.md#KenseiECS_ComponentPoolBase_ReservedComponents) stays 0), so a later [`ReserveEntities()`](KenseiECS.World.md#KenseiECS_World_ReserveEntities_System_Int32_) does not extend them. Under KENSEI_DEBUG growth past either argument is counted in [`GrowthsAfterReserve`](KenseiECS.World.md#KenseiECS_World_GrowthsAfterReserve) for every pool and filter. Allocation failures leave the world consistent, as with [`ReserveEntities()`](KenseiECS.World.md#KenseiECS_World_ReserveEntities_System_Int32_).
Removed in 3.0.
Exceptions
When an argument is negative.
When the world was destroyed.
When an array cannot be allocated, also for a size no array can have (int.MaxValue components with a filter in the world); the world stays usable, see the remarks.
ReserveEntities(int)
Reserve the world's own per-entity storage for entities entity slots (indices 0 to entities - 1): generations, alive flags, component counts, every mask word (and, with more than one mask word, the summary of the words in use) and the free-slot list, sized exactly, so that up to entities entities alive at once never grow them. Pools and filters are not touched, except the reserved ones: a pool reserved with Reserve() and a filter with a reserve (ReservedCount above 0) cover the reserved slots with their sparse (entity-indexed) side, extended here and by every later call. A filter's reserve taken from its types is capped at the slots, so it moves with them and its dense array can grow (a Entities span taken before is then invalid). No array shrinks; a repeated call only raises ReservedEntities.
public void ReserveEntities(int entities)Parameters
entities int
Number of entity slots to have room for. 0 does nothing.
Remarks
The world, the hot pools and the hot filters, nothing else: with this call and Pool<T>().Reserve(count) for every component type whose count changes during play, creating and destroying entities (at most entities alive at once), adding and removing those components (at most their reserve each) and entering and leaving the filters made of them allocates nothing. A filter whose Inc types are all reserved is reserved by them (see [`ReservedCount`](KenseiECS.Filter.md#KenseiECS_Filter_ReservedCount)), a filter created later included, so the filters systems create in Init need nothing. A pool or filter that was not reserved keeps its size and grows on demand. Creating a pool, a filter or a type in a new block of 64 type indices (one mask word per slot) allocates too: let the systems create them at load.
The cost is the world's per-entity arrays (about 13 bytes plus 8 bytes per 64 component types per slot, and 8 more once a type index of 64 or above is in use) and 4 bytes per slot for each reserved pool and filter. The obsolete [`Reserve()`](KenseiECS.World.md#KenseiECS_World_Reserve_System_Int32_System_Int32_) charged every pool and filter for the slots instead, singletons and the ones created later included.
Under KENSEI_DEBUG a later growth of the world's slots or free-slot list past the reserve, or of a reserved pool's or filter's arrays past theirs, is counted in [`GrowthsAfterReserve`](KenseiECS.World.md#KenseiECS_World_GrowthsAfterReserve) and, while EcsProfiler records this world, logged as a ProfileEventType.StorageGrown event. While the profiler records, the growth of a pool or filter that nothing reserved is logged too, marked "not reserved", and not counted: that is how a forgotten hot type shows.
Everything is allocated before it replaces the old storage, and [`ReservedEntities`](KenseiECS.World.md#KenseiECS_World_ReservedEntities) is raised last: if an allocation fails (`OutOfMemoryException`), the world stays consistent and usable, some arrays possibly grown, and reserves made afterwards do not try the failed size.
Call it at load time, like [`Warmup()`](KenseiECS.World.md#KenseiECS_World_Warmup); it allocates.
Exceptions
When entities is negative.
When the world was destroyed.
When an array cannot be allocated; the world stays usable, see the remarks.
SetName(Entity, string)
Attach a debug name to an entity, shown by the inspector and profiler. Does nothing unless KenseiECS is compiled with KENSEI_DEBUG.
public void SetName(Entity entity, string name)Parameters
entity Entity
name string
Remarks
The call itself is never removed, so its arguments are always evaluated: world.SetName(world.CreateEntity(...), "Player") creates the entity in every configuration. It is deliberately not [Conditional], which would drop the arguments with the call and silently skip their side effects without the define. A name built per call (string interpolation at spawn) is still built in release; wrap such a call in #if KENSEI_DEBUG if that allocation matters.
TryGetEntity(int, out Entity)
Handle for a slot index if that slot currently holds an alive entity. Safe for any index.
public bool TryGetEntity(int entityIndex, out Entity entity)Parameters
entityIndex int
entity Entity
Returns
Warmup()
Pre-touch pools and filters to trigger JIT compilation and memory allocation. Creates a temporary entity, adds a default component of every registered type (exercises Add paths, component masks, and filter insertion), then destroys it (exercises Remove paths and filter removal). Existing entities and their data are not touched. World event listeners and the profiler do not observe the temporary entity, but typed pool listeners (IComponentListener) and filter listeners (IFilterListener) do: they get OnAdded/OnEntityAdded and then OnRemoved/OnEntityRemoved for it, with default component values. If a listener destroys the temporary entity (a rule that destroys entities with no health fires on the default value), the remaining types go to a new temporary entity, never to the freed slot or to an entity the listener created in it. A type a listener already added to the temporary entity is skipped. If a listener throws, the temporary entity is still destroyed. The EventBuffer list pool is not filled (the added components are default, without lists): use Prewarm() for that, and ReserveEntities() and Reserve() to size storage for the peak. Call once before gameplay starts (e.g. during loading screen).
public void Warmup()