Have you ever pressed Find All References on an event in Unity and stared at an IDE window showing 15 subscribers scattered across a dozen separate files?
Early in my game development career, when I first learned about decoupling dependencies to prevent spaghetti code, I viewed events and message buses as silver bullets. Module A finishes its task and fires an event into space. Modules B, C, and D listen if they care. No direct references, no Inspector drag-and-drop, and you could move a module into another project without compiler errors. On an architectural whiteboard, it looked incredibly clean and satisfying.
That illusion lasted until the project entered full production and intermittent bugs began appearing. QA logged an elusive issue: “Occasionally when the player dies, the defeat screen does not appear, but enemies keep spawning indefinitely”.
I placed a breakpoint at the player death event. When execution paused, the debugger call stack was essentially blind: it showed only the internal mechanics of MulticastDelegate.Invoke(). It provided zero context regarding who initiated the state change, who was scheduled to handle it next, or whether an intermediate subscriber had mutated shared state midway through the invocation chain.
That was the moment I realized a fundamental engineering reality: Code decoupling always trades off directly against traceability. When you make systems so indirect that they lose all explicit ownership, the cost of debugging and refactoring rises exponentially.
This article examines the underlying runtime mechanics of three primary communication patterns in Unity: Message Buses, Scoped C# Events, and Interfaces with Dependency Injection, establishing a tiered communication strategy that balances architectural flexibility with deterministic debugging.
1. Under the Hood: C# MulticastDelegate and the Disconnected Call Stack
To understand why excessive indirection breaks debuggability, we need to inspect how the C# Runtime executes events in memory.
1.1. MulticastDelegate Mechanics and Hidden Allocation Costs
In C#, every event Action or event EventHandler is backed by an instance derived from System.MulticastDelegate. Internally, this delegate maintains an invocation list (_invocationList) containing pairs of target object references and method pointers:
- Synchronous Execution: When you call
OnPlayerDied?.Invoke(), the runtime does not run tasks asynchronously or on background worker threads. It iterates through the invocation array sequentially on the Unity Main Thread. If any single subscriber performs heavy calculations or throws an unhandled exception, every subsequent subscriber in the list is either delayed or completely skipped. - Non-Deterministic Execution Order: C# guarantees execution according to subscription order (
+=). However, in Unity, the initialization order of GameObjects across scenes and the invocation ofAwake()orOnEnable()is non-deterministic unless manually configured in Script Execution Order. Consequently, subscriber ordering is fragile and vulnerable to logic race conditions when two systems depend on receiving the notification first. - Managed Heap Allocations: Because delegates in C# are immutable, every
+=and-=operation creates a newMulticastDelegatearray on the Managed Heap. Frequently subscribing and unsubscribing within gameplay loops generates unnecessary Garbage Collector pressure.
1.2. The Problem of Call Stack Blindness
When modules communicate through a decoupled intermediary such as a global message bus (for example, GlobalMessageBus), direct linkage between the caller and receiver is severed:
flowchart TD
subgraph DirectCall["1. Direct Interface / DI Call"]
Caller1["CombatController"] -->|"DealDamage()"| Callee1["PlayerHealth"]
end
subgraph EventCall["2. Decoupled Message Bus"]
Caller2["CombatController"] -->|"Publish(DamageMsg)"| Bus["GlobalMessageBus"]
CalleeA["PlayerHealth"]
CalleeB["QuestTracker"]
CalleeC["SoundManager"]
end
Bus -.->|"Invoke delegate #1"| CalleeA
Bus -.->|"Invoke delegate #2"| CalleeB
Bus -.->|"Invoke delegate #3"| CalleeC
In the direct interface invocation model, checking the call stack in your debugger reveals an uninterrupted path:
CombatController.DealDamage() -> PlayerHealth.TakeDamage().
Every stack frame, parameter value, and caller origin is visible at a glance.
With a Message Bus, the call stack is broken:
CombatController -> MessageBus.Publish() -> Delegate.Invoke() -> Subscriber.
If a subscriber receives corrupt data, you cannot look up the stack trace to determine who published that message, why it was constructed with those parameters, or what state preceded the dispatch.
2. Comparing the Three Communication Paradigms
We can place Unity communication mechanisms across a trade-off spectrum: maximum indirection on one end, and strict compile-time transparency on the other.
flowchart LR
A["Global Message Bus\n(Highest Decoupling - Lowest Traceability)"] --- B["Scoped C# Event\n(Balanced Locality)"] --- C["Interface / DI\n(Tightest Contract - Highest Traceability)"]
2.1. Group 1: Global Message Bus (Event Aggregator)
- Mechanism: A centralized static service or singleton mediator that dispatches struct or class payloads based on type metadata or string identifiers.
- Strengths: Decouples direct references to zero. Publishers and subscribers know nothing about each other. Modules can be isolated or mocked easily during prototyping.
- Major Limitations:
- IDE navigation breaks down.
Find All Referencesidentifies message structs across the entire codebase rather than business logic call sites. - High risk of memory leaks: if a destroyed Unity GameObject fails to unsubscribe from a static bus, the GC Root in the bus holds the managed shell alive, creating zombie subscribers that continue receiving messages and throwing
MissingReferenceException.
- IDE navigation breaks down.
- Appropriate Use Cases: One-way, fire-and-forget notifications that carry no critical gameplay state:
- Audio playback requests.
- Analytics event tracking.
- Secondary visual polish (camera shake, controller haptics, achievement toasts).
2.2. Group 2: Scoped C# Events (Subject-Bound Observer)
- Mechanism: Events defined directly on the data owner (for example,
PlayerStatsModel.OnHpChanged). Observers require a reference to the specific subject instance to register callbacks. - Strengths:
- Preserves encapsulation: publishers remain unaware of who consumes the event.
- Traceability remains strong because events are bound to an identifiable instance with a clear lifecycle. Developers always know the exact data source.
- Limitations: Requires disciplined lifecycle cleanup (
-=) upon object destruction to prevent dangling delegate leaks. - Appropriate Use Cases: Internal state change notifications within a single feature boundary:
- Model-to-View synchronization in MVP or MVVM architectures.
- Parent-to-child component communication.
- Local entity attribute modifications (health points, mana reserves, inventory slots).
2.3. Group 3: Interfaces and Dependency Injection
- Mechanism: When Module A requires services from Module B, it requests an explicit
IModuleBcontract through its constructor orInitialize()method. All interactions occur through defined interface members. - Strengths:
- Maximum operational clarity and complete call stack continuity. Navigating to definitions or implementations takes a single IDE shortcut.
- Deterministic execution sequence controlled by orchestration code.
- Effortless unit testing via lightweight test doubles and mock implementations.
- Limitations: Requires boilerplate orchestration and a composition root to assemble dependencies during startup.
- Appropriate Use Cases: Core gameplay systems:
- Combat resolution and damage calculation pipelines.
- Match lifecycle controllers (GameMode, LevelFlow, WaveSpawner).
- Persistence and networking synchronization services.
3. Real-World Scenario: Refactoring a Game Over Flow
To examine the delicate balance between decoupling and traceability, consider the match termination sequence in a mobile top-down Roguelike Survival title (in the spirit of Vampire Survivors). The player maneuvers across an arena fighting hundreds of active enemies generated continuously by a WaveSpawner. When the player’s health drops to zero, the engine must execute a strict sequence: immediately halt monster generation, compute and lock final progression scores, transition to the defeat screen, play audio feedback, and flush telemetry payloads to analytics servers.
In a competitive live-ops environment, execution order between stopping active spawners and locking player scores must be completely deterministic. Any subtle race condition where monsters continue dealing damage or score increments occur after defeat triggers will compromise match integrity. This is precisely where blindly relying on an decoupled global message bus introduces unpredictable bugs that defy straightforward debugging.
3.1. Fragile Anti-Pattern: Over-Reliance on a Global Message Bus
In an unconstrained prototype, everything is dispatched via an untyped or global message bus:
using System;
using System.Collections.Generic;
// Shared payload definition
public struct PlayerDefeatedMessage
{
public int FinalScore;
public string DefeatReason;
}
// Static global message dispatcher
public static class GlobalMessageBus
{
private static readonly Dictionary<Type, List<Delegate>> _subscribers = new Dictionary<Type, List<Delegate>>();
public static void Subscribe<T>(Action<T> handler)
{
var type = typeof(T);
if (!_subscribers.ContainsKey(type))
{
_subscribers[type] = new List<Delegate>();
}
_subscribers[type].Add(handler);
}
public static void Publish<T>(T message)
{
var type = typeof(T);
if (_subscribers.TryGetValue(type, out var handlers))
{
foreach (var handler in handlers)
{
((Action<T>)handler)?.Invoke(message);
}
}
}
public static void ClearAll() => _subscribers.Clear();
}
The issue emerges when core gameplay logic relies entirely on this bus:
public class FragileCombatController
{
private int _score;
public FragileCombatController(int initialScore)
{
_score = initialScore;
}
public void OnPlayerHealthDepleted()
{
// Fire message blindly and hope receivers process it correctly
GlobalMessageBus.Publish(new PlayerDefeatedMessage
{
FinalScore = _score,
DefeatReason = "HP_DEPLETED"
});
}
}
In this setup, FragileCombatController cannot guarantee:
- Who is subscribed to this event.
- Whether
WaveSpawnerstops beforeGameModeManagerfinalizes score calculations. - How an exception inside an early listener affects subsequent handlers.
- How to write an isolated unit test verifying that “player death stops enemy spawning” without dealing with shared static state in
GlobalMessageBus.
4. Tiered Architecture: Structured Coordination and Automated Testing
Rather than forcing a single communication tool across an entire codebase, robust architecture segments communication according to operational criticality through an explicit coordinator (RobustCombatCoordinator in our code sample below, orchestrating IWaveSpawner, IGameModeFlow, and IEventDispatcher):
flowchart TD
Combat["RobustCombatCoordinator\nCentral Orchestrator"]
subgraph Tier1["Tier 1: Core Flow - Interface / DI"]
Spawner["IWaveSpawner"]
Mode["IGameModeFlow"]
end
subgraph Tier2["Tier 2: State Change - C# Event"]
HealthView["HealthBarView"]
end
subgraph Tier3["Tier 3: Side-Effects - Message Bus"]
Audio["AudioSystem"]
Analytics["AnalyticsSystem"]
end
Combat -->|"1. StopSpawning()"| Spawner
Combat -->|"2. HandleDefeat()"| Mode
Combat -->|"Event OnHpChanged"| HealthView
Combat -.->|"BroadcastDefeatEvent()"| Audio
Combat -.->|"BroadcastDefeatEvent()"| Analytics
4.1. Defining Explicit Domain Contracts
For mission-critical systems that dictate match rules, define clear contracts and supply them explicitly:
using System;
// Contract governing enemy wave lifecycle
public interface IWaveSpawner
{
bool IsSpawning { get; }
void StopSpawning();
}
// Contract managing match resolution
public interface IGameModeFlow
{
bool IsGameOver { get; }
int FinalRecordedScore { get; }
void HandleDefeat(string reason, int finalScore);
}
// Contract for decoupled side-effect notifications
public interface IEventDispatcher
{
void BroadcastDefeatEvent(int finalScore);
}
4.2. Deterministic Orchestration
An orchestration class coordinates these contracts, enforcing deterministic sequence and complete testability:
public class RobustCombatCoordinator
{
private readonly IWaveSpawner _spawner;
private readonly IGameModeFlow _gameMode;
private readonly IEventDispatcher _eventDispatcher;
public int CurrentScore { get; private set; }
public int CurrentHp { get; private set; }
// Scoped C# event for UI health bar updates
public event Action<int> OnHpChanged;
public RobustCombatCoordinator(
IWaveSpawner spawner,
IGameModeFlow gameMode,
IEventDispatcher eventDispatcher,
int initialHp,
int initialScore)
{
_spawner = spawner ?? throw new ArgumentNullException(nameof(spawner));
_gameMode = gameMode ?? throw new ArgumentNullException(nameof(gameMode));
_eventDispatcher = eventDispatcher ?? throw new ArgumentNullException(nameof(eventDispatcher));
CurrentHp = initialHp;
CurrentScore = initialScore;
}
public void ApplyDamage(int damage)
{
CurrentHp = Math.Max(0, CurrentHp - damage);
OnHpChanged?.Invoke(CurrentHp);
if (CurrentHp <= 0 && !_gameMode.IsGameOver)
{
// Step 1: Immediately halt enemy spawning to preserve game state
_spawner.StopSpawning();
// Step 2: Finalize match failure and lock final score
_gameMode.HandleDefeat("HP_DEPLETED", CurrentScore);
// Step 3: Broadcast secondary events for audio and telemetry
_eventDispatcher.BroadcastDefeatEvent(CurrentScore);
}
}
}
This design yields critical benefits:
- Execution order is 100% deterministic: waves stop spawning before match defeat logic calculates final rewards.
- The debugger call stack remains intact, eliminating blind spots during investigation.
- Automated testing is straightforward using lightweight test doubles.
4.3. Verifying the Orchestration Flow with Unit Tests
We can verify the entire defeat pipeline in milliseconds without loading Unity scenes or managing static singletons:
using NUnit.Framework;
[TestFixture]
public class RobustCombatCoordinatorTests
{
private class FakeWaveSpawner : IWaveSpawner
{
public bool IsSpawning { get; private set; } = true;
public void StopSpawning() => IsSpawning = false;
}
private class FakeGameModeFlow : IGameModeFlow
{
public bool IsGameOver { get; private set; } = false;
public int FinalRecordedScore { get; private set; } = 0;
public string DefeatReason { get; private set; } = "";
public void HandleDefeat(string reason, int finalScore)
{
IsGameOver = true;
FinalRecordedScore = finalScore;
DefeatReason = reason;
}
}
private class FakeEventDispatcher : IEventDispatcher
{
public int BroadcastedScore { get; private set; } = -1;
public int BroadcastCount { get; private set; } = 0;
public void BroadcastDefeatEvent(int finalScore)
{
BroadcastedScore = finalScore;
BroadcastCount++;
}
}
[Test]
public void ApplyDamage_FatalDamage_StopsSpawnerAndFinalizesGameMode()
{
var spawner = new FakeWaveSpawner();
var gameMode = new FakeGameModeFlow();
var dispatcher = new FakeEventDispatcher();
var coordinator = new RobustCombatCoordinator(
spawner,
gameMode,
dispatcher,
initialHp: 100,
initialScore: 450);
// Apply fatal damage
coordinator.ApplyDamage(damage: 120);
// Verify state and execution across core systems
Assert.AreEqual(0, coordinator.CurrentHp);
Assert.IsFalse(spawner.IsSpawning);
Assert.IsTrue(gameMode.IsGameOver);
Assert.AreEqual(450, gameMode.FinalRecordedScore);
Assert.AreEqual(1, dispatcher.BroadcastCount);
}
[Test]
public void ApplyDamage_NonFatalDamage_KeepsSpawnerRunningAndDoesNotTriggerGameOver()
{
var spawner = new FakeWaveSpawner();
var gameMode = new FakeGameModeFlow();
var dispatcher = new FakeEventDispatcher();
var coordinator = new RobustCombatCoordinator(
spawner,
gameMode,
dispatcher,
initialHp: 100,
initialScore: 200);
// Apply non-fatal damage
coordinator.ApplyDamage(damage: 30);
Assert.AreEqual(70, coordinator.CurrentHp);
Assert.IsTrue(spawner.IsSpawning);
Assert.IsFalse(gameMode.IsGameOver);
Assert.AreEqual(0, dispatcher.BroadcastCount);
}
}
5. Architectural Trade-off Matrix
Every architectural pattern trades specific advantages against operational overhead:
| Evaluation Criteria | Global Message Bus | Scoped C# Event | Interface / DI |
|---|---|---|---|
| Decoupling Degree | Highest (Zero mutual knowledge) | Moderate (Observer couples to publisher instance) | Lowest (Both couple to shared Interface contract) |
| Traceability | Lowest (Call stack severed, difficult to trace publishers) | High (Publisher instance clearly identified) | Maximum (Continuous call stack, IDE navigation intact) |
| Execution Sequence | Non-deterministic (Dictated by runtime registration order) | Deterministic according to delegate assignment += | Completely deterministic via orchestration logic |
| Memory / GC Profile | Potential leaks via stale static references, payload boxing | Delegate allocation overhead if subscribed continuously | Negligible heap impact, zero garbage collection spikes |
| Testability | Low (Requires static state cleanup between runs) | Moderate (Requires concrete publisher instances) | High (Direct interface mock substitution) |
| Target Scope | Audio, Analytics, Haptics, Achievements | UI Data Binding, Model-to-Presenter, Child-to-Parent | Combat rules, Save systems, Match controllers |
6. Practical Rules for Modular Architecture in Unity
When structuring communication between game modules, consider three foundational guidelines:
- Prioritize Traceability over Decoupling for Core Gameplay Logic: Match win/loss conditions, scoring mechanics, state persistence, and AI wave spawning form the backbone of your project. These domains demand strict execution ordering and immediate breakpoint navigation. Favor explicit interfaces injected via constructors.
- Use Scoped C# Events for UI and Model Synchronization: Data models own domain state and broadcast mutations via events. Views or presenters observe these events to update graphics. This keeps models free from UI dependencies while maintaining a single, obvious source of truth.
- Reserve Message Buses Exclusively for One-Way Side Effects: When an event occurs and the caller does not care who handles it, expects no return data, and match logic remains unaffected whether listeners execute or fail (such as playing an audio clip, triggering gamepad vibration, or recording telemetry), a Message Bus delivers its highest architectural value.
- The Six-Month Debugging Question: Before introducing delegate indirection or an event bus channel, ask: “Six months from now, if a logic defect surfaces here, can a newly onboarded engineer locate the root cause in the IDE within five minutes?”. If the answer is no, replace the indirection with an explicit interface.


