Skip to content
ToanLB
Go back

Event, Observer, DI, or Message Bus: The Trade-off Between Decoupling and Traceability in Unity

~11 min read
Event, Observer, DI, or Message Bus: The Trade-off Between Decoupling and Traceability in Unity

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:

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)

2.2. Group 2: Scoped C# Events (Subject-Bound Observer)

2.3. Group 3: Interfaces and Dependency Injection


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:


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:

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 CriteriaGlobal Message BusScoped C# EventInterface / DI
Decoupling DegreeHighest (Zero mutual knowledge)Moderate (Observer couples to publisher instance)Lowest (Both couple to shared Interface contract)
TraceabilityLowest (Call stack severed, difficult to trace publishers)High (Publisher instance clearly identified)Maximum (Continuous call stack, IDE navigation intact)
Execution SequenceNon-deterministic (Dictated by runtime registration order)Deterministic according to delegate assignment +=Completely deterministic via orchestration logic
Memory / GC ProfilePotential leaks via stale static references, payload boxingDelegate allocation overhead if subscribed continuouslyNegligible heap impact, zero garbage collection spikes
TestabilityLow (Requires static state cleanup between runs)Moderate (Requires concrete publisher instances)High (Direct interface mock substitution)
Target ScopeAudio, Analytics, Haptics, AchievementsUI Data Binding, Model-to-Presenter, Child-to-ParentCombat rules, Save systems, Match controllers

6. Practical Rules for Modular Architecture in Unity

When structuring communication between game modules, consider three foundational guidelines:

  1. 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.
  2. 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.
  3. 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.
  4. 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.

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.