Services and lifetimes
Components do not look services up by hand. A service is an object the engine or a brick provides, such as the scene manager, the input source or the simulation clock, and a component receives it by declaring a property that the engine fills in. Your own shared objects work the same way once you register them. Some services also run code while the game runs; these are subsystems, and each one lives for the application, the gameplay session or a single scene.
Injecting a service
Mark a property with [InjectService]. The engine sets it when the component is attached to its node, before OnAttached and OnAwake run, so the value is ready in those callbacks:
using System.Text.Json.Serialization;
using Silk.NET.Input;
namespace Usercode;
public class PauseOnSpace : Component
{
[InjectService, JsonIgnore]
public SimulationClock Simulation { get; private set; } = null!;
[InjectService(Optional = true), JsonIgnore]
public IInputSource? Input { get; private set; }
public override void OnUpdate(float deltaTime)
{
if (Input is not null && Input.WasKeyPressed(Key.Space)) Simulation.TimeScale = 0;
}
}
Three rules come from the engine:
- Mark the property
[JsonIgnore]. A scene does not save an injected service, and the engine rejects an injected property without it. - A property with a private setter is the usual form, as in the examples. The engine fills it, the Inspector never shows it, and nothing edits it.
- A required service that is not registered makes attaching the component fail with an error that names the service. Set
Optional = truefor services a headless server may not have, such asIInputSourcein the example above.
The services a game registers itself, which are available to every component, include:
| Type | What it gives you |
|---|---|
ISceneManager |
Loading, unloading and instantiating scenes (scenes). |
IAssetLoader |
Loading assets at runtime (assets). |
IInputSource |
The input device (input). |
IInputActions |
Named input actions (input). |
SimulationClock |
The fixed-step clock: time scale and pause (game loop). |
ISessionLifetime |
The running session: restart it, and find a scene's subsystems. |
GameLoopScheduler |
Gameplay waits and returns to the game thread (async). |
Bricks add their own services in the same way, for example the physics and audio bricks.
Registering your own service
Put a class that implements IEngineServiceModule in your game's assembly. The engine finds it when the game starts, in Studio's Play Mode and in an exported game alike, and calls ConfigureServices once. The module needs a public parameterless constructor, and the class must not be abstract:
using Microsoft.Extensions.DependencyInjection;
namespace Usercode;
public sealed class Inventory
{
public int Gold { get; set; }
}
public sealed class GameModule : IEngineServiceModule
{
public void ConfigureServices(IServiceCollection services) => services.AddSingleton<Inventory>();
}
A component injects it like any engine service:
[InjectService, JsonIgnore]
public Inventory Inventory { get; private set; } = null!;
AddSingleton makes one instance for the whole run of the application. It is never rebuilt when the session restarts, so keep per-run state in a session subsystem instead, described below. When two registrations name the same service type, the one registered last wins, and the game's own module is registered after the bricks it uses.
Lifetimes
Every subsystem belongs to one of three lifetimes. They nest: the application lives longest, then the session, then each scene.
| Lifetime | Created | Ends | Use it for |
|---|---|---|---|
LifetimeScope.Application |
When the game starts | When the game ends | Things that outlive every restart and scene change: the clock, input and the simulation loop. |
LifetimeScope.Session |
When the game starts | When the game ends, or when the session restarts | State a fresh run must start without: tweens, a physics world, a match timer. |
LifetimeScope.Scene |
When a scene loads | When that scene unloads | State tied to one loaded level or screen, such as its spawners. |
A session survives scene loads. Loading a scene in Single mode unloads the other scenes, and their scene subsystems end, but the session keeps running. The engine runs at most one session at a time.
To start a fresh run without restarting the application, call Restart on ISessionLifetime:
[InjectService, JsonIgnore]
public ISessionLifetime Lifetime { get; private set; } = null!;
public void PlayAgain() => Lifetime.Restart();
The restart applies at the end of the current frame. It unloads every scene, ends the session's subsystems, creates them again, and loads the game's first scene. Pass a scene asset id to Restart to open that scene instead. Application-lifetime services are not touched.
Choose the shortest lifetime that every user of a subsystem still lives for. The rules are checked when the game starts:
- A subsystem may depend only on subsystems of the same or a longer lifetime. A session subsystem that needs a scene subsystem is rejected with an error that names both types.
- Each subsystem is created after the ones it depends on and stopped before them.
Writing a subsystem
A subsystem implements ISubsystem, which has Start and Stop, and usually one of the game-loop interfaces so it runs in a phase. The game loop page covers the phases:
namespace Usercode;
public sealed class MatchTimer : IGameLoopSubsystem
{
public double Elapsed { get; private set; }
public GameLoopPhases Phases => GameLoopPhases.FixedTick;
public void Start() { }
public void Stop() { }
public void Run(GameLoopPhase phase, in LoopTime time) => Elapsed += time.DeltaTime;
}
Register it from the game's module, in the lifetime you chose. The factory receives the scope, so a subsystem can reach the services it needs:
public sealed class GameModule : IEngineServiceModule
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Inventory>();
services.AddSubsystem(LifetimeScope.Session, static scope => new MatchTimer());
}
}
The last argument of AddSubsystem lists the subsystem types it depends on, which the scope creates first. A subsystem that another one depends on must be registered in a lifetime at least as long, as described above.
A component reaches a session or application subsystem by injecting its type, because the engine resolves those through the live session. A scene subsystem is found through the scene instead. Get the scene's scope from ISessionLifetime.SceneOf and ask it for the subsystem:
var scene = Lifetime.SceneOf(Node!);
if (scene is not null && scene.TryGet<Spawner>(out var spawner)) spawner.Reset();
Gotchas
- An injected value is the one live when the component is attached. Components in scenes are destroyed when their scene unloads, and a restart unloads every scene, so they are attached again with the new session's services. A service registered with
AddSingletonis the same object across restarts. - The engine starts, ticks and stops subsystems on the game's main thread only.
- A plain singleton has no
StartorStop. Use a subsystem for anything that opens a resource and must close it. A subsystem that implementsIDisposableis disposed when its lifetime ends, after it stops. - A scene can load and unload many times inside one session, so state that must survive those loads belongs in the session, not the scene.
Next steps
- Game loop — the phases a subsystem joins and the order they run in.
- Async — waits that resume on the game thread.
- Components — the component lifecycle and attributes.
- Bricks — sharing services and subsystems between projects.