←All patterns
Creational

Singleton

Guarantee a class has exactly one instance and give everyone a single, well-known way to reach it.

What Is It?

A Singleton restricts a class to one instance and exposes it through a static access point, usually a property called Instance. Whoever asks first causes it to exist; everyone after that receives the very same object.

In Unity the twist is that most singletons are MonoBehaviours living on a GameObject. That means the "one instance" rule has to survive scene loads (DontDestroyOnLoad) and has to cope with a designer accidentally dropping a second copy into another scene — the newcomer must destroy itself.

A typical example is a GameManager that tracks score, pause state and the current level. The player, the HUD and every enemy can call GameManager.Instance.AddScore(10) without anyone wiring references in the Inspector.

When Is It Used?

Use it for genuinely global services where a second copy would be a bug: an audio mixer controller, a save system, a platform/achievements bridge, or a top-level game state manager.

It is handy in prototypes and game jams where speed of wiring matters more than testability — one static property beats dragging references across twenty prefabs.

Avoid it as a default way to share data. If many systems reach into Instance for everything, you get hidden dependencies and hard-to-test code; consider dependency injection or ScriptableObject services once the project grows.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Singleton Pattern
instances0created0accesses0
Scene: Level1
DontDestroyOnLoad
◆ Player
client
▤ HUD
client
✦ Enemy
client
Instance == null
Console
Press a button to see what happens…

Code

Assets / Scripts / Creational/ Singleton ›ScoreClient.cs
using UnityEngine;

namespace Patterns.Creational.Singleton
{
    /// <summary>
    /// A client that needs the GameManager. No Inspector reference:
    /// it simply asks for GameManager.Instance.
    /// </summary>
    public class ScoreClient : MonoBehaviour
    {
        [SerializeField] private int pointsPerPickup = 10;

        private void OnEnable()
        {
            GameManager.Instance.ScoreChanged += OnScoreChanged;
        }

        private void OnDisable()
        {
            // Instance may be null while the application is quitting.
            var gm = GameManager.Instance;
            if (gm != null) gm.ScoreChanged -= OnScoreChanged;
        }

        private void OnTriggerEnter(Collider other)
        {
            if (other.CompareTag("Pickup"))
            {
                GameManager.Instance.AddScore(pointsPerPickup);
                Destroy(other.gameObject);
            }
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
                GameManager.Instance.SetPaused(!GameManager.Instance.IsPaused);

            if (Input.GetKeyDown(KeyCode.N))
                GameManager.Instance.LoadLevel("Level2");
        }

        private void OnScoreChanged(int score) => Debug.Log($"Score: {score}");
    }
}
3 files · namespace Patterns.Creational.SingletonC# · UTF-8 · LF

Before & After

Real-world smell: a game manager found by searching the scene and copied into every scene. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Every scene has its own GameManager so it can be played on its own, and Instance is just FindFirstObjectByType<GameManager>(). Each copy calls DontDestroyOnLoad, so after a few level loads several managers are alive at once.

Which one the search returns is not defined: the score can go into one copy while the HUD listens to another. The search also walks the scene on every call, which adds up when it sits in Update or in dozens of pickups.

✓ What changed

  • GameManager now derives from Singleton<GameManager>, and the FindFirstObjectByType property is gone.
  • The base Awake keeps the first instance and destroys any later duplicate, so dropping a manager into every scene for testing is now safe.
  • Instance is cached after the first lookup, and the base class handles DontDestroyOnLoad and clears the reference in OnDestroy.
  • The trade-off stays: it is still global state, so every caller keeps a hidden dependency on it. Use it for truly game-wide state and pass references explicitly where you can.
GameManager.Before.cs → GameManager.After.cs+5/−9
11 using System;
22 using UnityEngine;
33 using UnityEngine.SceneManagement;
44
55 namespace Patterns.Creational.Singleton
66 {
77 /// <summary>
8− /// Without a proper Singleton: a manager is dropped into every scene
9− /// for convenience, and callers search the scene to find "the" one.
8+ /// With Singleton&lt;T&gt;: exactly one manager survives scene loads,
9+ /// the reference is cached, and any later duplicate removes itself.
1010 /// </summary>
11− public class GameManager : MonoBehaviour
11+ public class GameManager : Singleton<GameManager>
1212 {
13− // Searches the loaded scenes on every single call.
14− public static GameManager Instance => FindFirstObjectByType<GameManager>();
15−
1613 public int Score { get; private set; }
1714 public bool IsPaused { get; private set; }
1815
1916 public event Action<int> ScoreChanged;
2017
21− private void Awake()
18+ protected override void Awake()
2219 {
23− // Each scene's copy survives the next load, so they pile up.
24− DontDestroyOnLoad(gameObject);
20+ base.Awake(); // destroys this copy if another one already exists
2521 Debug.Log($"GameManager ready (id {GetInstanceID()})");
2622 }
2723
2824 public void AddScore(int amount)
2925 {
3026 Score += amount;
3127 ScoreChanged?.Invoke(Score);
3228 }
3329
3430 public void SetPaused(bool paused)
3531 {
3632 IsPaused = paused;
3733 Time.timeScale = paused ? 0f : 1f;
3834 }
3935
4036 public void LoadLevel(string sceneName)
4137 {
4238 SceneManager.LoadScene(sceneName);
4339 }
4440 }
4541 }

Advantages & Disadvantages

+ Advantages

  • Single access point — no Inspector wiring, any script can find the service.
  • Lazy creation means the object only exists once something actually needs it.
  • With DontDestroyOnLoad it naturally carries state (score, settings) across scenes.

− Disadvantages

  • Creates hidden global dependencies; it is hard to see which classes rely on it.
  • Unit testing is awkward because the static instance leaks between tests.
  • Initialization order issues: calling Instance from another Awake can hit a half-initialised object.

Tips

  1. 01Use a generic Singleton<T> base class so every manager gets the same duplicate-handling and persistence logic for free.
  2. 02In Awake, if Instance already exists and is not this, call Destroy(gameObject) immediately — this handles the "manager placed in every scene" case.
  3. 03Unity APIs are main-thread only, so a MonoBehaviour singleton rarely needs locking. For plain C# singletons accessed from worker threads, use Lazy<T> for thread-safe lazy initialisation.
  4. 04Clear the static reference in OnDestroy and, with Enter Play Mode Options (no domain reload), reset statics via [RuntimeInitializeOnLoadMethod].
  5. 05Guard against OnApplicationQuit ordering: other objects destroyed after the manager may call Instance and accidentally spawn a fresh one.