Systems & SharedData
Systems
A system is a class implementing any combination of three interfaces. The runner detects which ones it implements when you Add it:
csharp
class MySystem : IInitSystem, IRunSystem, IDestroySystem {
public void Init(World world, SharedData shared) { }
public void Run(World world) { }
public void Destroy(World world) { }
}| Interface | Method | Called |
|---|---|---|
IInitSystem | Init(World, SharedData) | once per SystemsRunner.Init(); again after Destroy() or after a failed Init |
IRunSystem | Run(World) | every frame, from SystemsRunner.Run() |
IDestroySystem | Destroy(World) | once per completed Init, from SystemsRunner.Destroy(); from the rollback of a failed Init only if it also implements IInitSystem and its Init completed (see the lifecycle contract) |
Do the setup work in Init: build filters, cache pools, fetch services from SharedData. Run then only iterates.
Generated Init
Mark the fields of a partial system class with [Inc], [Exc], [Any], [Pool], [Group] or [Shared] and the source generator writes Init for you. See Generated Init.
SharedData
Typed container for shared services. No reflection, explicit access. Register instances before the runner initializes and pass the container to the root runner:
csharp
var shared = new SharedData();
shared.Add(new TimeService());
shared.Add(new SpawnConfig { Max = 100 }, "enemies");
shared.Add(new SpawnConfig { Max = 20 }, "pickups");
var systems = new SystemsRunner(world, shared)
.Add(new SpawnSystem());Systems receive it in Init:
csharp
class SpawnSystem : IInitSystem {
TimeService _time;
SpawnConfig _enemyConfig;
public void Init(World world, SharedData shared) {
_time = shared.Get<TimeService>(); // throws if not registered
_enemyConfig = shared.Get<SpawnConfig>("enemies");
if (shared.TryGet(out SpawnConfig pickups, "pickups")) {
// optional service: false when not registered
}
}
}- Entries are keyed by type and an optional string key, so several instances of one type can coexist (
"enemies","pickups"). Adding again under the same type and key replaces the instance. - The type is the generic argument of
Add<T>, not the runtime type of the instance: an object added asAdd<IService>(impl)is found byGet<IService>(), not byGet<Impl>(). GetthrowsKeyNotFoundExceptionwhen nothing is registered;TryGetreturns false instead.- Values must be reference types (
where T : class). - A nested runner constructed without
SharedDatainherits its parent's (see nested runners).
