Singletons vs Service Locator
Some systems exist once: audio, saving, the game state, analytics. Every script needs to reach them. The three common answers in Unity are the singleton, the service locator and dependency injection, and the debate between them never ends. Here is what each costs.
The MonoBehaviour singleton
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance { get; private set; }
void Awake()
{
if (Instance != null && Instance != this) { Destroy(gameObject); return; } // a duplicate from another scene
Instance = this;
DontDestroyOnLoad(gameObject);
}
void OnDestroy()
{
if (Instance == this) Instance = null;
}
public void PlaySfx(AudioClip clip) { /* ... */ }
}
// anywhere:
// AudioManager.Instance.PlaySfx(clip);Good: trivial to write and use; fine for game jams and small games.
Costs: every caller is hard-wired to one concrete class; tests can't substitute a fake; initialization order bugs ("Instance is null" when called from another Awake); and with domain reload disabled, static fields keep stale values between Play sessions unless you reset them.
The "lazy" variant that creates itself with new GameObject().AddComponent<T>() on first access hides when it's created. That's convenient, but it also creates managers during scene teardown ("Some objects were not cleaned up when closing the scene").
The service locator
A service locator is one registry that maps an interface to an implementation. Callers ask for IAudioService, not AudioManager, so tests and platforms can register something else.
using System;
using System.Collections.Generic;
// Game boot: register real services.
Services.Register<IAudioService>(new ConsoleAudio());
Services.Register<ISaveService>(new MemorySave());
new Player().CollectCoin();
// A test (or a headless server build): swap the audio service for a silent one.
Services.Reset();
Services.Register<IAudioService>(new SilentAudio());
Services.Register<ISaveService>(new MemorySave());
new Player().CollectCoin();
Console.WriteLine(quot;silent audio heard {((SilentAudio)Services.Get<IAudioService>()).Calls} call(s)");
// Forgetting a registration fails loudly at the call site.
Services.Reset();
try { new Player().CollectCoin(); }
catch (InvalidOperationException e) { Console.WriteLine(e.Message); }
interface IAudioService { void Play(string cue); }
interface ISaveService { void Set(string key, int value); int Get(string key); }
class ConsoleAudio : IAudioService { public void Play(string cue) => Console.WriteLine(quot;audio: {cue}"); }
class SilentAudio : IAudioService { public int Calls; public void Play(string cue) => Calls++; }
class MemorySave : ISaveService
{
readonly Dictionary<string, int> data = new();
public void Set(string k, int v) => data[k] = v;
public int Get(string k) => data.GetValueOrDefault(k);
}
static class Services
{
static readonly Dictionary<Type, object> map = new();
public static void Register<T>(T service) where T : class => map[typeof(T)] = service;
public static T Get<T>() where T : class =>
map.TryGetValue(typeof(T), out var s) ? (T)s : throw new InvalidOperationException(quot;No service registered for {typeof(T).Name}");
public static void Reset() => map.Clear();
}
class Player
{
public void CollectCoin()
{
var save = Services.Get<ISaveService>();
save.Set("coins", save.Get("coins") + 1);
Services.Get<IAudioService>().Play("coin");
Console.WriteLine(quot;coins = {save.Get("coins")}");
}
}audio: coin
coins = 1
coins = 1
silent audio heard 1 call(s)
No service registered for ISaveService
In Unity, register services from a bootstrap: a component in a first "Boot" scene, or a method with [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)], which runs before the first scene loads even when you press Play in a level scene. Clear the registry there too, so it works with domain reload disabled.
Costs: dependencies are still hidden inside methods (Player doesn't declare that it needs audio); a missing registration is a runtime error, not a compile error.
Dependency injection
DI frameworks (VContainer, Zenject/Extenject, Reflex) make dependencies explicit: a component declares [Inject] void Construct(IAudioService audio) and a scope object wires everything at startup. You get testability and visible dependencies, at the price of a framework, a learning curve and some startup cost. Larger teams often find it worth it; small games rarely need it.
A pragmatic recommendation
- Prefer plain serialized references (
[SerializeField] AudioManager audio;) where the wiring is local and visible in the Inspector. - Use event channels for "something happened" messages.
- For a handful of truly global services, a service locator registered from a bootstrap, behind interfaces, is a good middle ground.
- If you keep singletons, keep few of them, make them read-only from outside, and never have one singleton's
Awakedepend on another.
Test yourself
What is the main advantage of a service locator over a concrete singleton?
- It's faster
- Callers depend on an interface, so implementations can be swapped (tests, platforms)
- It removes the need for MonoBehaviours
- It serializes automatically
Why does a singleton's Awake destroy itself when Instance is already set?
- To save memory
- Another scene loaded a duplicate; only the first instance should survive
- Awake runs twice
- Unity requires it
Which attribute runs bootstrap code before the first scene loads?
[ExecuteAlways][RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)][InitializeOnLoad](runtime)[DefaultExecutionOrder(-1)]