Generated Init
The package ships a Roslyn source generator (Plugins/KenseiECS.Generators.dll, picked up by Unity 2021.2+ and by any .NET project that references the generator). Mark the fields of a partial system class and the generator writes Init for you:
public partial class MovementSystem : IRunSystem {
[Inc(typeof(Position), typeof(Velocity))] [Exc(typeof(Frozen))]
private Filter _moving;
[Pool] private ComponentPool<Position> _positions;
[Pool] private ComponentPool<Velocity> _velocities;
[Group] private Group<Position, Velocity> _group;
[Shared] private GameConfig _config;
[Shared("enemies")] private SpawnConfig _enemies;
partial void OnInit(World world, SharedData shared) {
// optional: runs after the fields above are filled
}
public void Run(World world) {
foreach (int e in _moving) {
_positions.Get(e).X += _velocities.Get(e).X * _config.Speed;
}
}
}The generated partial adds IInitSystem (unless the class already declares it), so the runner calls the generated Init like any other:
var world = new World();
var shared = new SharedData();
shared.Add(new GameConfig());
shared.Add(new SpawnConfig { Max = 100 }, "enemies");
var systems = new SystemsRunner(world, shared)
.Add(new MovementSystem()); // registered as an init system via the generated partial
systems.Init(); // calls the generated InitWhat gets generated
The generated Init fills the marked fields in declaration order, then calls OnInit. For MovementSystem it is equivalent to:
// What the generator writes for MovementSystem, spelled out by hand
public class HandWrittenMovementSystem : IInitSystem, IRunSystem {
private Filter _moving;
private ComponentPool<Position> _positions;
private ComponentPool<Velocity> _velocities;
private Group<Position, Velocity> _group;
private GameConfig _config;
private SpawnConfig _enemies;
// virtual because the class is not sealed (a sealed one gets a plain public void Init)
public virtual void Init(World world, SharedData shared) {
_moving = world.Filter().Inc<Position>().Inc<Velocity>().Exc<Frozen>().End();
_positions = world.Pool<Position>();
_velocities = world.Pool<Velocity>();
_group = world.Group<Position, Velocity>();
_config = shared.Get<GameConfig>();
_enemies = shared.Get<SpawnConfig>("enemies");
// ...then OnInit(world, shared) if the class implements it
}
public void Run(World world) { }
}| Attribute | Field type | Injected with |
|---|---|---|
[Inc(...)], [Exc(...)], [Any(...)] | Filter | world.Filter().Inc<...>().Exc<...>().Any<...>().End() |
[Pool] | ComponentPool<T> | world.Pool<T>() |
[Group] | Group<...> | world.Group<...>() |
[Shared] / [Shared("key")] | any | shared.Get<T>() / shared.Get<T>("key") — see SharedData |
[Inc], [Exc] and [Any] take a list of component types and combine on one field. A type in [Exc] that is also in [Inc] or [Any] is the error KECS019: the filter would throw when Init builds it (types that differ only in tuple element names, W<(int a, int b)> and W<(int x, int y)>, are one type). A type the compiler cannot resolve, a typo or a component that another source generator adds, is left to the compiler: the filter is written with the name as given, and every other system keeps its Init. Write a type that another generator adds with its namespace, since the generated file has no using directives. Up to 2.4.0 [Inc(typeof(Typo))] made the generator throw (warning CS8785), and no system of the assembly got its Init. OnInit is optional: if you do not implement it, the call is removed by the compiler.
The attributes are recognised by their classes, not by how they are written: [Pool], [KenseiECS.Pool], [PoolAttribute] and a using alias (using Inject = KenseiECS.PoolAttribute; with [Inject], also as a global using in another file) all work. Up to 2.4.0 an attribute written through an alias was not noticed, and the field stayed null with no diagnostic.
Only instance fields written in the class are injected. A static field is left alone (warning KECS014), and so is the backing field of an auto-property marked [field: Pool] (warning KECS015): declare a field and return it from the property. The same holds for [field: Pool] on a field-like event (warning KECS015). A field takes one kind of attribute: a filter ([Inc]/[Exc]/[Any]), [Pool], [Group] or [Shared]; with two kinds on one field the first in that order is applied and the other is reported (warning KECS016).
Nested system classes work as long as every containing type is a partial class or struct (not a record or interface):
public partial class Gameplay { // every containing type must be partial too (KECS005)
public partial class FreezeSystem : IRunSystem {
[Inc(typeof(Position))] [Any(typeof(Frozen), typeof(Velocity))]
private Filter _targets;
public void Run(World world) { }
}
}The generated part is written to a file of its own, so it must be able to name the class: a file-local system class (file partial class, C# 11), a class nested in a file-local type and a file-local component type in [Inc], [Exc] or [Any] are the error KECS017. The class must also leave the name Init to the generated method: a field, property, event or nested type named Init, and a class named Init, are the error KECS018. So is a type parameter named Init (class Spawner<Init>).
Inheritance
A system with injected fields can derive from another one. Both classes are partial, and each gets its own fields filled and its own OnInit called. The derived fields are filled first, then the base Init runs (the base fields and the base OnInit), then the derived OnInit: the base OnInit, and any virtual method it calls, already sees the derived fields, and the derived OnInit sees them all.
public abstract partial class DamageSystemBase : IRunSystem {
[Pool] protected ComponentPool<Health> HealthPool;
partial void OnInit(World world, SharedData shared) {
// runs first: HealthPool is filled, and so are the fields of a derived class
}
public abstract void Run(World world);
}
public partial class PoisonSystem : DamageSystemBase {
[Inc(typeof(Health), typeof(Poisoned))]
private Filter _poisoned;
partial void OnInit(World world, SharedData shared) {
// runs second: HealthPool and _poisoned are both filled
}
public override void Run(World world) {
foreach (int e in _poisoned) {
HealthPool.Get(e).Value -= 1;
}
}
}The generated Init is public virtual in every class that is not sealed (a sealed class keeps the plain public void Init), whether anything derives from it or not, so a subclass in another assembly, or one compiled only under a define such as UNITY_EDITOR, finds the same Init in every build. The derived class's generated Init overrides it and calls base.Init between its own fields and its OnInit:
// What the generator writes for the pair above (fully qualified names shortened)
class HandWrittenDamageSystemBase : IInitSystem {
protected ComponentPool<Health> HealthPool;
// virtual in every class that is not sealed, with or without subclasses
public virtual void Init(World world, SharedData shared) {
this.HealthPool = world.Pool<Health>();
// OnInit(world, shared);
}
}
class HandWrittenPoisonSystem : HandWrittenDamageSystemBase {
private Filter _poisoned;
public override void Init(World world, SharedData shared) {
this._poisoned = world.Filter().Inc<Health>().Inc<Poisoned>().End();
base.Init(world, shared);
// OnInit(world, shared);
}
}The chain works through any number of levels, through plain intermediate classes without injected fields and across assemblies; generic bases (PoolSystem<T>) work too. Registering the derived system is enough: the runner calls Init through IInitSystem, and the override runs the whole chain. Hand-written classes between two generated systems may override Init themselves, any number of them in a row, also over a generated base in the 2.1 layout (its Init is declared new); up to 2.4.0 a second override in a row, or one over such a base, was a false KECS006 on the derived system. A derived system over a hand-written override of a generated Init that failed with its own error gets no second one.
A hand-written base that implements IInitSystem (directly or through an interface that extends it, such as IGameSystem : IInitSystem) is chained the same way when its Init is public virtual (or abstract, then the generated override has no base.Init call):
public abstract class WorldSystemBase : IInitSystem, IRunSystem {
protected World World;
// public virtual (or abstract): the generated Init of a subclass overrides it
public virtual void Init(World world, SharedData shared) {
World = world;
}
public abstract void Run(World world);
}
public partial class RegenSystem : WorldSystemBase {
[Pool] private ComponentPool<Health> _health;
// generated: public override void Init(...) { _health = ...; base.Init(...); OnInit(...); }
public override void Run(World world) { }
}The generated override always calls base.Init(world, shared) itself (except over an abstract base Init), so the class must not: any base.Init written in its own declarations, in OnInit or elsewhere, is KECS012, because it would run the base Init (fields and OnInit) a second time. The check is purely syntactic: every base.Init counts, whatever overload it would bind to; a base.Init inside a nested type belongs to that type and does not count. A hand-written class without injected fields, such as an intermediate public override void Init between two generated systems, calls base.Init as usual: an override of a generated Init without that call leaves the base fields null and skips the base OnInit, which is the warning KECS013 (also syntactic; for a base in another assembly it is recognised only by injected fields visible from the derived assembly, protected or public). The call must arrive as well: when C# binds every base.Init call of such an override to another Init overload, the generated Init does not run either, and that is KECS013 as well, reported on the call. An overload takes the call when it is declared below the class that first declares Init(World, SharedData): in a hand-written class between, or in the generated base itself when its generated Init is an override (C# looks an override up at the class that first declares the method, so Init(World, SharedData, int x = 0), Init(World, object) or Init(World, params SharedData[]) next to it wins); rename the overload. An overload next to a generated Init that is the first declaration, or above it, loses to that Init and is fine, and so is an override with one call that arrives. A base.Init that is only named (a delegate) is not judged. The calls are judged as the compiler will bind them once the generated code exists. Up to 2.4.0 such an override compiled without a word and the base fields stayed null.
KECS006 reports the setups that cannot be chained: a base Init that is not virtual, sealed, not public or implemented explicitly (void IInitSystem.Init, also when the class has a public virtual void Init next to it that the explicit one does not call: the runner calls the explicit one; hand-written overrides of that public Init in classes between do not change this, 2.2.1 took them for chainable and left the fields null; a derived class that lists IInitSystem itself is still chained over them, since the interface then maps to its generated Init; the same holds over hand-written overrides of a public virtual void Init that a class between declares itself, below a base with the explicit one or as a new Init: such a class is chained over them too, so a base.Init in its OnInit is KECS012 and an Init overload in between is KECS006, unless a base above that Init has injected fields, see the 2.1 layout below), a class in between that declares its own non-override Init (including another overload such as Init(World, object), Init(World, SharedData, int x = 0) or int Init(World, SharedData): C# would bind the generated base.Init(world, shared) to it and the base Init would never run; rename it) or a member named Init that is not a method, and a base from another assembly whose Init is not virtual (a hand-written one, or one generated by KenseiECS 2.2.1 or older, which made it virtual only when that assembly had generated subclasses; rebuild that assembly). A generic helper such as Init<T>(World, SharedData) whose type parameter the two arguments cannot infer does not take the call and is allowed. When the chained base Init is itself a hand-written override (or a generated one), C# looks the call up at the class that first declares that Init: an overload on the chained base or on any class up to that one takes the call too and is KECS006 as well (2.2.1 checked only the classes between and let the call go to the overload); an overload in the class with the first declaration loses to it and is allowed.
A base whose explicit IInitSystem.Init does a part of its own and then calls its public virtual void Init (Init(world, shared) or this.Init(world, shared) in the explicit one) is chained like a base with only the public one, in either member order: the runner calls the explicit Init, and its call reaches the generated override, so the order is the base's own part, the derived fields, the base Init, the derived OnInit. 2.2.0 and 2.2.1 chained it only when the public Init came first in the class. The call is read from source, so for a base in another assembly it is still KECS006, also with hand-written overrides of the public Init between it and the derived class.
Over a base Init that cannot be overridden, the 2.1 layout still works: list IInitSystem (or an interface that extends it) among the derived class's own bases and call base.Init(world, shared) from OnInit; the generated Init then re-implements the interface (declared new), and the base runs only through your call. A class in this layout without a base.Init call is KECS006 when the base Init would never run: when that Init is the one the runner reaches through IInitSystem.Init (also a sealed or protected override in a class between, which 2.2.1 missed, and a new Init whose class lists IInitSystem itself), or when a base has injected fields (of a base in another assembly only the protected and public ones are seen, as for KECS013, so a base there with only private injected fields is not reported). Not reported: an explicit base IInitSystem.Init, which base.Init cannot reach anyway, and a new Init in between that does not implement IInitSystem.Init, with no injected fields above it. Such an Init is taken for an unrelated method: the generated Init replaces the interface's Init without a diagnostic, and the Init it hides does not run (a base.Init in OnInit would call the new one, not the hidden one).
The call must also arrive: a base.Init(world, shared) that C# binds to another Init overload of a class in between (Init(in World, SharedData), Init(World, object), Init(World, SharedData, int x = 0), Init(World, params SharedData[])) does not run the base Init and is KECS006 like a missing call; rename the overload. An overload declared next to the base Init takes the call too when that Init is a hand-written override of a generated one (a sealed override, for example): C# looks the override up at the generated base, above the overload. Up to 2.4.0 such a class compiled and the base Init was skipped. Over an abstract base Init there is nothing to skip, and such a call is simply a call of that overload.
A class that lists IInitSystem over a hand-written override of an Init that hides the one of a base with injected fields (public new virtual void Init in a class between, overridden further down) is this layout as well, not a chained one: without the base.Init call it is KECS006. Up to 2.4.0 it was chained without a word, and the fields of that base were filled only if the hiding Init happened to call its own base.
A base with its own OnInit
A hand-written base may already have an OnInit(World, SharedData) of its own, typically a virtual hook that its Init calls. The generated part then declares no partial void OnInit over it (that would hide the hook). Override the hook, and it runs once, after the derived fields are filled: from the base Init, when the generated Init calls one that can call the hook (the hook is declared in that base or in one of its bases), and from the generated Init otherwise — over a base that is not a system, over an abstract base Init, or when the hook is declared in a hand-written class between a generated base and the derived class. 2.2.1 did not compile those three cases (CS0111). A generated base in between counts by what its own generated Init does: when that Init calls no base (its own base is not a system, or has an abstract Init) and does not call the hook itself, the derived class's generated Init calls the override. Up to 2.4.0 the override was left to the base Init there and never ran. A generated base in another assembly is judged the same way from its compiled Init, when it is recognised as generated, by protected or public injected fields; with only private ones it is taken for a hand-written base that calls the hooks it can see. In the 2.1 layout (the derived class lists IInitSystem over a base Init that cannot be overridden) an override of a hook that this base Init can call is KECS006: the generated Init would call it, and the base.Init that OnInit must call would run it again; make the base Init public virtual, or put the setup into partial void OnInit instead of overriding the hook.
public abstract class ViewSystemBase : IInitSystem, IRunSystem {
protected World World;
public virtual void Init(World world, SharedData shared) {
World = world;
OnInit(world, shared); // the hook subclasses set themselves up in
}
protected virtual void OnInit(World world, SharedData shared) { }
public abstract void Run(World world);
}
public partial class HealthBarSystem : ViewSystemBase {
[Pool] private ComponentPool<Health> _health;
// no partial OnInit is generated over the hook: the base Init calls this
// override once, and _health is already filled
protected override void OnInit(World world, SharedData shared) {
}
public override void Run(World world) { }
}A partial void OnInit written in the derived class anyway is still declared and runs after the base Init, next to the hook. An OnInit(World world, SharedData shared) written without partial (in any class with injected fields) is called by the generated Init like the partial one, unless it overrides a hook that the chained base Init calls; a generated base can offer such a protected virtual hook to its subclasses.
Upgrading from 2.1
On 2.1 a derived system called the base Init itself from OnInit (often with IInitSystem listed again). Where the generator now chains the base (a generated base, or a hand-written public virtual Init), that call is KECS012: delete the line. The generated Init makes the call after the derived fields and before the derived OnInit, so the base Init still sees the derived fields, as it did when the call stood at the top of OnInit.
public partial class PoisonSystem : DamageSystemBase {
[Inc(typeof(Health), typeof(Poisoned))] private Filter _poisoned;
partial void OnInit(World world, SharedData shared) {
- base.Init(world, shared);
// derived setup
}
}An OnInit that held only that call can be removed. Code that stood in OnInit before the call now runs after the base Init; what the base needs earlier belongs in the constructor or in a virtual method the base calls. Listing IInitSystem again is harmless. Over a base Init that cannot be overridden (not virtual, or from an assembly built by 2.2.1 or older) keep the call: that is the 2.1 layout, and without the call it is KECS006.
Upgrading from 2.2.0 and 2.2.1
- A derived system in another assembly than its generated base is now chained there too (the base
Initis virtual), so abase.Initcall kept in itsOnInitfor the 2.1 layout isKECS012: delete it. - The derived fields are filled before the base
Initinstead of after it, and the baseOnInitsees them. A[Shared]field of the derived class is therefore read before the baseInitruns: an object that the baseOnInitadds toSharedDatais not there yet, add it when buildingSharedData. - The
Initof a class that is notsealedisvirtualeven without subclasses: a hand-written subclass that declarespublic void Init(World, SharedData)withoutoverrideornewgets CS0114 instead of CS0108 (both warnings; it still hides the baseInit).
Diagnostics
KECS001 to KECS012 and KECS017 to KECS019 are errors. KECS013 to KECS016 are warnings: the code compiles, but something marked for injection is not injected. KECS020, an error too, reports a failure of the generator itself on one class. A project that turns warnings into errors (TreatWarningsAsErrors) fails on KECS013 to KECS016 as well: fix the field, or keep them warnings with <WarningsNotAsErrors>KECS013;KECS014;KECS015;KECS016</WarningsNotAsErrors>.
| Id | Cause | Fix |
|---|---|---|
| KECS001 | The class has injected fields but is not partial. | Add the partial modifier. |
| KECS002 | The class declares Init(World, SharedData) next to injected fields, either as a method (static or not, with any return type) or as an explicit void IInitSystem.Init(...). An Init with other parameters is an overload and is fine; up to 2.4.0 any Init with two parameters was reported. | Remove Init; put custom setup into partial void OnInit(World world, SharedData shared). |
| KECS003 | An attribute is on a field of the wrong type: [Inc]/[Exc]/[Any] not on Filter, [Pool] not on ComponentPool<T>, [Group] not on Group<...>, [Shared] on a value type (struct, int). Nullable annotations such as Filter? are fine. | Change the field type or the attribute. |
| KECS004 | A filter field has [Exc] without [Inc] or [Any]; exclude-only filters are not supported. | Add [Inc] or [Any]. |
| KECS005 | The system class is nested in a type that is not partial. | Add partial to every containing type. |
| KECS006 | A class with injected fields derives from a class whose Init the generated one cannot override and call (see Inheritance): the base Init is not virtual/abstract, is sealed, is not public or is an explicit IInitSystem.Init (also next to a public virtual void Init that it does not call, with or without hand-written overrides of that Init in between); a class in between declares its own Init that does not override it, another Init overload that the generated base.Init(world, shared) would bind to (on a class in between, or on the chained base and above it up to the class that first declares the overridden Init), or a member named Init that is not a method; or the base comes from another assembly where its Init is not virtual (generated there by 2.2.1 or older without subclasses). Also a class that lists IInitSystem itself over such a base (the 2.1 layout) and has no base.Init call, or whose base.Init(world, shared) C# binds to another Init overload (of a class in between, or next to a base Init that is a hand-written override of a generated one), so the base Init would never run (injected fields of a base in another assembly count only when protected or public), or that overrides a base OnInit hook this base Init can call. The message names the reason. | Make the base Init public virtual, remove the hiding Init or the explicit implementation, rename the overload or member, or rebuild the other assembly with this version. Otherwise list IInitSystem in the derived class's bases and call base.Init(world, shared) from OnInit. |
| KECS007 | A filter field lists no component types in [Inc] or [Any] (for example an empty [Inc]). | Add at least one required or alternative type. |
| KECS008 | A type in [Inc], [Exc] or [Any] is not a struct implementing IComponent. | List component types only. |
| KECS009 | An injected field is readonly; the generated Init assigns it. | Remove readonly. |
| KECS010 | A record or struct has injected fields; injection is generated only for classes. | Make the system a partial class. |
| KECS011 | The system class is nested in a record or an interface. | Move it into a class or struct, or to namespace level. |
| KECS012 | A derived class with injected fields writes base.Init (in OnInit or any other member of its own declarations) while its generated Init overrides the base Init and already calls it, between the derived fields and OnInit (see Inheritance). Recognised by syntax, whatever overload the call binds to. | Remove the base.Init call; the base Init still runs before OnInit. Rename a hand-written base helper that is also called Init. |
| KECS013 | Warning. A hand-written class overrides Init(World, SharedData) of a generated base (directly or through hand-written overriding classes) and has no base.Init in its own declarations, or only base.Init calls that C# binds to another Init overload (of a class in between, or of the generated base when its Init is an override; see Inheritance), so the generated Init never runs: the base fields stay null and the base OnInit is skipped. A missing call is recognised by syntax, a call that goes elsewhere by what the compiler binds it to once the generated code exists; a generated base in another assembly is recognised only by its protected or public injected fields. Up to 2.4.0 a call that an overload takes was not reported. | Call base.Init(world, shared) from the override; rename an Init overload that takes the call. If replacing the base Init is intended (a test double, for example), suppress the warning with #pragma warning disable KECS013. |
| KECS014 | Warning. A static field has an injection attribute. The generated Init fills the fields of the system instance, so the field is not injected and stays null. Reported also for a type that has no other injected field. | Remove static, or remove the attribute and assign the field yourself. |
| KECS015 | Warning. An auto-property or a field-like event has [field: Pool] (or another injection attribute on its backing field). The backing field is not injected, and the property stays null. Up to 2.4.0 the attribute on an event was not reported. | Declare a field with the attribute and return it from the property; remove the attribute from an event. |
| KECS016 | Warning. A field has two kinds of injection attribute, for example [Pool] and [Shared], or [Inc] and [Pool]. One is applied (a filter attribute first, then [Pool], [Group], [Shared]), the other is ignored. [Inc], [Exc] and [Any] together are one kind. | Keep one kind. |
| KECS017 | The system class is file-local (file partial class, C# 11) or nested in a file-local type, or [Inc], [Exc] or [Any] lists a file-local component type. The generated Init is written to another file, which cannot see a file-local type; up to 2.4.0 the generated code did not compile. | Remove the file modifier. |
| KECS018 | The system class has a member named Init that is not a method (a field, property, event or nested type) or a type parameter named Init, or the class itself is named Init. The generated Init(World, SharedData) cannot be declared next to it (CS0102, CS0542); up to 2.4.0 the generated code did not compile. A method named Init with other parameters is an overload and is fine. | Rename the member, the type parameter or the class. |
| KECS019 | A filter field lists the same component type in [Exc] and in [Inc] or [Any] (tuple element names do not make a different type). FilterBuilder.End() rejects such a filter, so up to 2.4.0 the generated Init threw InvalidOperationException. Reported for every class with such a field, also one that no runner ever initialises. | Remove the type from one of the attributes. |
| KECS020 | The generator itself failed on this class (an exception, named in the message), and the class gets no Init; the other classes are generated as usual, and a class derived from it gets no second error. Up to 2.4.0 any such failure ended the whole run with the warning CS8785 and no system of the assembly got its Init. | Fix the compiler errors in the class first (the generator may meet code it cannot read). If none are left, it is a bug of the generator: report it with the declaration of the class. |
