Skip to content
ToanLB
Go back

Why Large Projects Avoid Singleton Even Though It's Convenient

~10 min read
Why Large Projects Avoid Singleton Even Though It's Convenient

In the early days of game development with Unity, or when rushing to build a quick prototype before a tight deadline, typing .Instance feels like second nature. Need sound effects? Call SoundManager.Instance.Play(). Need to add score? Call GameManager.Instance.AddScore(). Need player health? Call PlayerData.Instance.Hp.

At the beginning, this approach feels remarkably productive: no dragging references across the Inspector, no passing dependencies through constructors, and instant global access from any script in the codebase.

However, as the project scales into a multi-year live-service production with dozens of levels, complex gameplay systems, and multiple engineers collaborating, this initial convenience compounds into heavy technical debt. Memory usage climbs after each scene transition, NullReferenceException crashes appear intermittently during initialization, and writing automated unit tests becomes nearly impossible.

This article breaks down the root issues behind overusing Singletons in Unity - from low-level runtime memory management and the engine lifecycle to software architecture - and shares practical modular refactoring strategies for growing codebases.


1. Low-Level Mechanics: C# Runtime and Unity Lifecycle

To understand why Singletons frequently turn into technical bottlenecks, we need to inspect how the C# Runtime (Mono/IL2CPP) and Unity Engine interact to manage memory and object lifecycles.

flowchart TD
    subgraph CSharpRuntime["C# Runtime (Mono / IL2CPP)"]
        GCRoot["Static GC Root (_instance)"] -->|Permanently holds reference| SingObj["Singleton Instance (Managed Heap)"]
        SingObj -->|Field holds reference| HeavyRes["AudioClips / Textures (Native Memory)"]
        SingObj -->|Event invocation list holds| LeakedShell["Destroyed MonoBehaviour (Leaked Managed Shell)"]
    end

    subgraph UnityLifecycle["Unity Lifecycle"]
        A["Scene Unload / UnloadUnusedAssets"]
        B["Awake() / OnEnable() Race Condition"] -->|Calls Instance before init| NullEx["Intermittent NullReferenceException"]
        C["OnDestroy() / OnApplicationQuit()"] -->|Lazy loading spawns new GameObject| Zombie["Zombie Object in Hierarchy"]
    end

    A -.->|Cannot reclaim Native Memory| HeavyRes
    A -.->|Traps Managed Shell on Heap| LeakedShell

Static Variables as GC Roots and Two Classic Memory Leak Scenarios

In the C# runtime, a static field (such as _instance) lives for the entire lifetime of the AppDomain and is treated by the Garbage Collector as an immortal GC Root. During garbage collection cycles, the collector traverses the reference graph starting from GC Roots and never reclaims any object reachable from them.

Given Unity’s dual-memory architecture (split between the C# Managed Heap and the underlying Native C++ Engine memory), a DontDestroyOnLoad Singleton commonly introduces memory leaks through two distinct mechanisms:

  1. Leaked Managed Shells via C# Events (Publisher-Subscriber Leak): In .NET’s MulticastDelegate implementation, the event publisher holds direct references to all subscriber instances inside its invocation list. When scene-bound MonoBehaviour scripts subscribe to an event exposed by a persistent Singleton (GameManager.Instance.OnScoreChanged += OnScoreUpdated) and forget to unsubscribe (-=) inside OnDestroy(), unloading the scene creates a half-dead state:
    • The underlying Native C++ object is destroyed by the engine (so component == null evaluates to true due to Unity’s overloaded == operator).
    • However, the C# Managed Shell and every array or collection referenced by its fields remain pinned on the Managed Heap via the Singleton’s invocation list.
  2. Blocking Native Memory Cleanup of Heavy Assets: When a Singleton holds direct field references to heavy assets such as AudioClip, Texture2D, or Sprite without clearing them across level transitions, Resources.UnloadUnusedAssets() sees active references originating from a GC Root. Consequently, tens of megabytes of uncompressed audio and texture data in Native C++ memory can never be freed.

As the object graph anchored to static GC Roots grows across scene transitions, each Boehm GC or Incremental GC Mark phase must traverse a steadily expanding tree of uncollectable references, increasing mark duration and triggering noticeable GC spikes.

Initialization Race Conditions Across Awake() and OnEnable()

Unity provides no guarantee regarding the execution order of Awake() across different GameObjects in a scene unless manually configured in Script Execution Order (which becomes unmaintainable as projects expand).

Crucially, in Unity’s initialization lifecycle, Awake() and OnEnable() on a single GameObject can execute sequentially before Awake() is called on the next GameObject in the scene. If a component subscribes to AudioManager.Instance.OnMuteChanged += ... inside its OnEnable(), and the AudioManager GameObject has not executed its Awake() yet, an immediate NullReferenceException occurs. These bugs are notoriously difficult to reproduce because they depend on scene serialization order.

The Zombie Object Phenomenon During Scene Unloads or Application Quit

Many developers implement Singletons using lazy instantiation: checking if (_instance == null) inside the Instance getter and calling new GameObject("GameManager") on demand.

This pattern backfires during scene teardown or when closing the application (OnApplicationQuit):


2. Architectural Bottlenecks at Scale

Beyond engine lifecycle pitfalls, widespread .Instance calls from modules like UIController or CombatController introduce major architectural hurdles when working in larger teams.

flowchart TD
    subgraph Coupling["Tight Coupling and Hidden Dependencies"]
        UI["UIController"] -->|Calls directly| SM["SoundManager.Instance"]
        SM -->|Hidden dependency| DM["DataManager.Instance"]
        DM -->|Hidden dependency| CF["Config.Instance"]
        Combat["CombatController"] -->|Hard coupled| GM["GameManager.Instance"]
    end

    subgraph StateMutation["Uncontrolled Global State Mutation"]
        Enemy["EnemyController"] -->|Mutates directly| Score["GameManager.score"]
        Quest["QuestManager"] -->|Mutates directly| Score
        Combo["ComboSystem"] -->|Mutates directly| Score
    end

Hidden Dependencies and Module Reusability Friction

Inspecting a class’s serialized fields or constructor often gives the false impression that the module is self-contained. In reality, methods inside the class may be calling four or five global Singletons behind the scenes.

This creates a domino effect when attempting to reuse code:

Barriers to Automated Unit Testing and Mocking

Consider a combat attack flow (computing damage against enemy armor, awarding player score, and triggering hit audio) that needs fast unit test coverage.

If the method directly calls GameManager.Instance.CurrentEnemyDefense and SoundManager.Instance.PlaySfx():

Loss of Ownership Over Global State

Singletons grant unrestricted read/write access to any script in the project. When a state variable like PlayerScore is exposed publicly on GameManager.Instance:

When QA reports intermittent score calculation bugs, tracing which script mutated the variable at which frame becomes exhausting because there is no single source of truth or clear ownership over state transitions.


3. Code Demo: Before and After Refactoring

To understand where Singletons hit an architectural wall in automated testing, let us examine a very common production scenario: We are building an isometric Action RPG for PC and mobile. When the player executes a melee attack or ability, the combat system must calculate net damage after mitigating against target armor, play an auditory hit impact SFX, and update combo points for the session score.

In a live production environment, combat calculations and score accumulation represent core gameplay rules that iterate continuously across balance patches. We need to verify them quickly via automated CI/CD unit tests without instantiating an entire heavyweight graphics Scene. Furthermore, secondary services like audio and scoring must remain modular (such as muting audio entirely during headless testing or automated regressions). Tying this entire pipeline directly to GameManager.Instance and SoundManager.Instance (MonoBehaviour) makes independent unit testing nearly impossible.

Initial Approach: Convenient but Tightly Coupled

In this initial prototype implementation, the controller is tied to MonoBehaviour and reaches out to global Singletons directly:

using UnityEngine;

public class CombatController : MonoBehaviour
{
    public void DealDamage(int baseDamage)
    {
        // 1. Hidden dependency on GameManager for defense stats
        int defense = GameManager.Instance.CurrentEnemyDefense;
        int finalDamage = Mathf.Max(1, baseDamage - defense);

        // 2. Direct call to SoundManager
        SoundManager.Instance.PlaySfx("Hit_Sound");

        // 3. Direct mutation of global state
        GameManager.Instance.PlayerScore += finalDamage * 10;
        
        Debug.Log($"Dealt {finalDamage} damage.");
    }
}

The DealDamage method above cannot be tested in isolation without setting up a Unity Scene and initializing every referenced Singleton.


Decoupling Core Logic with Dependency Injection

To make the system modular and testable, we separate responsibilities into three parts:

  1. Define focused interfaces representing specific capabilities (IEnemyStatsProvider, IAudioService, IScoreTracker).
  2. Extract the combat workflow into a pure C# class (CombatProcessor) that receives its dependencies explicitly via constructor injection.
  3. Keep CombatController (MonoBehaviour) as a thin scene coordinator that delegates execution to CombatProcessor.
using System;
using UnityEngine;

// 1. Define narrow interfaces for each required capability
public interface IEnemyStatsProvider
{
    int Defense { get; }
}

public interface IAudioService
{
    void PlaySfx(string soundName);
}

public interface IScoreTracker
{
    void AddScore(int amount);
}

// 2. Pure C# domain logic, 100% independent of UnityEngine
public class CombatProcessor
{
    private readonly IEnemyStatsProvider _enemyStats;
    private readonly IAudioService _audioService;
    private readonly IScoreTracker _scoreTracker;

    public CombatProcessor(
        IEnemyStatsProvider enemyStats,
        IAudioService audioService,
        IScoreTracker scoreTracker)
    {
        _enemyStats = enemyStats ?? throw new ArgumentNullException(nameof(enemyStats));
        _audioService = audioService;
        _scoreTracker = scoreTracker;
    }

    public int ExecuteAttack(int baseAttack)
    {
        int finalDamage = Math.Max(1, baseAttack - _enemyStats.Defense);

        _audioService?.PlaySfx("Hit_Sound");
        _scoreTracker?.AddScore(finalDamage * 10);

        return finalDamage;
    }
}

// 3. Thin MonoBehaviour acting as a scene bridge
public class CombatController : MonoBehaviour
{
    private CombatProcessor _combatProcessor;

    public void Initialize(CombatProcessor combatProcessor)
    {
        _combatProcessor = combatProcessor ?? throw new ArgumentNullException(nameof(combatProcessor));
    }

    public void DealDamage(int baseDamage)
    {
        if (_combatProcessor == null)
        {
            Debug.LogError("[CombatController] Not initialized via Initialize()!");
            return;
        }

        _combatProcessor.ExecuteAttack(baseDamage);
    }
}
flowchart LR
    subgraph SceneLayer["Scene Layer (MonoBehaviour)"]
        Combat["CombatController"]
    end

    subgraph CoreLogic["Core Logic (Pure C#)"]
        Processor["CombatProcessor"]
    end

    subgraph Abstractions["Interfaces"]
        IStats["IEnemyStatsProvider"]
        IAudio["IAudioService"]
        IScore["IScoreTracker"]
    end

    subgraph Implementations["Concrete Implementations"]
        EnemyMono["EnemyStats"]
        AudioMgr["SoundService"]
        ScoreMgr["ScoreService"]
    end

    Combat -->|delegates to| Processor
    Processor -->|depends on| IStats
    Processor -->|depends on| IAudio
    Processor -->|depends on| IScore
    EnemyMono -.->|implements| IStats
    AudioMgr -.->|implements| IAudio
    ScoreMgr -.->|implements| IScore

Writing Fast In-Memory Unit Tests

Because CombatProcessor is a pure C# class depending only on interfaces, we can verify both damage calculation and side effects (audio playback and score tracking) using lightweight test doubles in under a millisecond without loading any Unity Scene:

using NUnit.Framework;

[TestFixture]
public class CombatProcessorTests
{
    private class FakeEnemyStats : IEnemyStatsProvider
    {
        public int Defense { get; set; }
    }

    private class SpyAudioService : IAudioService
    {
        public string LastPlayedSound { get; private set; }
        public void PlaySfx(string soundName) => LastPlayedSound = soundName;
    }

    private class SpyScoreTracker : IScoreTracker
    {
        public int TotalScore { get; private set; }
        public void AddScore(int amount) => TotalScore += amount;
    }

    [Test]
    public void ExecuteAttack_AttackHigherThanDefense_DealsDamageAndAddsScore()
    {
        var stats = new FakeEnemyStats { Defense = 30 };
        var audio = new SpyAudioService();
        var score = new SpyScoreTracker();
        var processor = new CombatProcessor(stats, audio, score);

        int damage = processor.ExecuteAttack(baseAttack: 100);

        Assert.AreEqual(70, damage);
        Assert.AreEqual(700, score.TotalScore);
        Assert.AreEqual("Hit_Sound", audio.LastPlayedSound);
    }

    [Test]
    public void ExecuteAttack_DefenseHigherThanAttack_ClampsMinimumOneDamage()
    {
        var stats = new FakeEnemyStats { Defense = 50 };
        var score = new SpyScoreTracker();
        var processor = new CombatProcessor(stats, audioService: null, scoreTracker: score);

        int damage = processor.ExecuteAttack(baseAttack: 10);

        Assert.AreEqual(1, damage);
        Assert.AreEqual(10, score.TotalScore);
    }
}

4. Architectural Trade-Off Comparison

No architectural pattern is a silver bullet. Every approach balances initial setup speed against long-term maintainability:

CriteriaSingleton (.Instance)Direct SerializeFieldDependency Injection (VContainer / Zenject)Event-Driven (ScriptableObject Events)
Initial Setup TimeVery fastSimpleRequires container/scope configurationModerate
Unit TestabilityVery hard to mockModerateHighly flexible and isolatedEasy to decouple
Dependency VisibilityHidden inside methodsVisible in InspectorExplicit in constructorsFully decoupled
Lifecycle ControlProne to GC roots & zombie objectsManaged by Unity Scene/PrefabManaged deterministically by ScopeScene-agnostic, requires unsubscription
Trade-offs / RisksAccumulates technical debt, hard to scale across teamsPrefab merge conflicts and broken Inspector linksMore boilerplate files, requires AOT stripping awareness on IL2CPPHarder to trace call stacks and listener execution order
Best Suited ForShort prototypes, stateless utilitiesSmall games, local prefab componentsMedium-to-large production projectsUI updates, achievements, cross-module notifications

5. When Is Singleton Still a Pragmatic Choice?

Singleton itself is not inherently evil - using it as a global mutable state container for gameplay systems is what causes pain. In production, Singleton remains a pragmatic choice in specific scenarios:

For core gameplay systems in long-term projects, replacing habitual .Instance calls with explicit dependencies and pure C# domain classes requires a bit more upfront thought about ownership. In return, fast unit tests, predictable lifecycles, and modular boundaries keep the engineering team moving fast as the project grows.


Share this post:
Lương Bảo Toàn

Luong Bao Toan

I work in HMI Automotive and Game development, sharing knowledge, hands-on experience, and stories I find interesting throughout my journey.

Did this article bring you value?

If this article helped your work, or you simply enjoyed it and want to support me, you can

Buy me a coffee

Related Articles

Comments & Discussions

Powered by Giscus

Get New Posts via Email

Subscribe to stay updated and never miss new posts from me.

* No spam. You can unsubscribe at any time with a single click.