DEV Community

Cover image for Observer Pattern in Unity: Instance Class or Static Class?
Toàn Lương Bảo
Toàn Lương Bảo

Posted on Originally published at toanlb.dev on

Observer Pattern in Unity: Instance Class or Static Class?

Observer Pattern in Unity: Instance Class or Static Class?

Whenever a team sets up the core architecture for a new Unity project, one early design decision quickly sparks debate: how should systems communicate via the Observer Pattern or an Event Bus? Specifically, when designing an Observer system from scratch, should it be implemented as a regular instance class or a static class?

Early in a Unity developer's career, the natural instinct often leans toward a static class. The appeal is obvious: with an instance class, you have to manage object instantiation, wire references through constructors or avoiding Singletons as projects scale, and track the bus's own lifecycle. If wired poorly, reference chains can get messy fast. A static class, by contrast, lets any script publish or subscribe directly by class name without passing references around.

Yet as a game grows across dozens of scenes, dynamic popups, and live updates, that convenience begins to show cracks. In practice, making an event system static does not automatically make it safer. In fact, with the Observer Pattern, an uncleaned static event often introduces far more insidious memory and state bugs than a scoped instance class ever would.


1. Under the Hood in the CLR: Why Static Events Leak Across Scenes

To understand why static does not shield an Observer system from memory leaks, we need to look at how the .NET CLR stores C# delegates under the hood.

How MulticastDelegate Holds Reverse Strong References

In C#, when a PlayerHudView subscribes via GlobalCombatBus.OnScoreChanged += hudView.HandleScoreChanged, the compiler allocates an Action<int> delegate (derived from MulticastDelegate). Inside that delegate, the _target field (or entries inside _invocationList) holds a direct strong reference to hudView.

That creates a critical ownership inversion: the Publisher holds a strong reference to the Subscriber, not the other way around.

flowchart LR
    subgraph SG_STATIC["Static Class Event Bus (AppDomain Lifetime)"]
        direction TB
        GC["GC Root (Static Field)"] -->|"Retained in _invocationList"| S1["Destroyed Subscriber"]
        S1 -->|"Native C++ dead, C# Shell alive"| L1["Managed Heap Leak + Dirty State"]
    end
    subgraph SG_INSTANCE["Scoped Instance Class (Match / Screen Scope)"]
        direction TB
        OW["Scope Owner (MatchContext)"] -->|"Owns explicitly"| BUS["Instance EventBus (IDisposable)"]
        BUS -->|"Calls Dispose() on Match End"| CL["Clears _invocationList -> GC reclaims all"]
    end
    L1 -.->|"Refactor to Scoped Bus"| OW

Three Consequences of Over-Extended Static Events

  1. Managed Shells Stay Alive After Destroy(gameObject): Suppose an EnemyMarkerUI in Scene 1 subscribes to a static event, and the developer forgets to -= before switching to Scene 2 or destroying that GameObject. Unity destroys the underlying C++ native object, so marker == null evaluates to true. However, because the static event is anchored directly to a global GC Root, the C# Garbage Collector cannot reclaim the Managed Shell of EnemyMarkerUI or any objects it references. Worse, the next time that event fires in Scene 2, the stale callback still executes against a dead native pointer and throws a MissingReferenceException.
  2. Stale Subscribers Survive When Domain Reload Is Disabled: When developers enable Enter Play Mode Options and disable Reload Domain in the Unity Editor for faster iteration, the CLR AppDomain is not reset between Play sessions. Every static event retains its previous subscriber list across Play runs unless explicitly cleared via [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)].
  3. Zero Isolation for Parallel Unit Testing: When all features read and write through a single static class, leftover state from Test A bleeds directly into Test B, making isolated or parallel test execution brittle.

2. The Real Question: Not Static vs Instance, but Scope and Ownership

Once you understand the delegate reference graph, the architectural decision stops being about choosing static for convenience or instance just to sound more "architectural." The real question is: What scope does this event belong to, and who owns its lifecycle?

To navigate the trade-offs between Decoupling and Traceability across Events and Message Buses cleanly, follow this ownership decision flow:

flowchart TD
    Start["Design a new Observer event channel"] --> Q1{"Does the event live for the entire App lifetime?"}
    Q1 -->|"Yes (Analytics, Auth, Audio)"| Q2{"Need multiple instances or isolated DI mocking?"}
    Q2 -->|"No multiple instances needed"| A1["Controlled Static Class<br/>Reset via SubsystemRegistration"]
    Q2 -->|"Need DI / Mocking / Multiple contexts"| A2["Application-Root Instance Class<br/>Injected via Service / Constructor"]
    Q1 -->|"No (Tied to Match, Scene, or UI Screen)"| A3["Scoped Instance Class (IDisposable)<br/>Owner creates & calls Dispose() on exit"]

When Is a static class Reasonable?

A static Event Hub is a pragmatic choice when all three criteria hold:

  • The signal is genuinely application-wide: network connectivity changes, global audio settings, or analytics milestones.
  • It carries no per-match or per-scene mutable state.
  • The channels are strictly typed and curated (preventing it from turning into a "global dumping ground" where unrelated systems fire arbitrary events), backed by a Domain Reload reset method.

When Should You Choose an Instance Class?

Any event tied to a gameplay match, a specific scene, or a UI screen (such as combat hits, wave progression, item pickups, or handling Late Join synchronization in the Observer Pattern) belongs in a Scoped Instance Class implementing IDisposable:

  • Explicit Ownership: It is immediately obvious which object creates and owns the bus (e.g., MatchSessionContext).
  • Centralized Cleanup (Safety Net): When a match ends or a scene unloads, the owner calls matchBus.Dispose(). Every internal _listeners reference is wiped at once. Even if a child UI widget forgets to unsubscribe in OnDestroy(), the publisher immediately drops its reference so the GC can reclaim everything cleanly.

3. Implementing Scoped Instance Bus vs Static Hub and Verifying GC Reclamation with NUnit

Consider a mobile Arena Roguelike where players cycle repeatedly between the Lobby, 3-minute combat arenas, and Upgrade screens. Application-level Analytics events must stay active across the whole app session, whereas combat events (damage dealt, enemy defeated, wave cleared) exist strictly within a single arena match.

To isolate these lifecycles and prove deterministic memory cleanup with automated tests, we structure the solution around four pure C# types:

  1. EnemyDefeatedEvent: A custom readonly struct payload representing an in-match enemy defeat signal.
  2. SubscriptionToken: An IDisposable handle returned on subscription that guarantees idempotent cleanup (calling Dispose() multiple times never throws or removes unrelated listeners). Keep this token's lifetime tied to the subscriber itself rather than storing it in a longer-lived external container without disposing it.
  3. ScopedEventBus<TPayload>: An IDisposable instance class tied to a Match or UI Screen scope, utilizing a reusable _dispatchBuffer for zero GC allocations on the normal Publish() path. Calling Dispose() wipes _listeners and _dispatchBuffer, severs every strong reference to subscribers, and guards subsequent Subscribe / Publish calls with ObjectDisposedException.
  4. GlobalAppEventHub: A controlled static class reserved for application-wide signals, decorated with [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] via ResetOnSubsystemRegistration so subscribers never leak across Play Mode sessions when Domain Reload is off.

Below is the complete implementation alongside an NUnit [TestFixture] test suite (including a WeakReference GC reclamation test proving the subscriber stays alive while the bus is active and is collected right after Dispose()):

using System;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;

public readonly struct EnemyDefeatedEvent
{
    public int EnemyId { get; }
    public int ScoreReward { get; }

    public EnemyDefeatedEvent(int enemyId, int scoreReward)
    {
        EnemyId = enemyId;
        ScoreReward = scoreReward;
    }
}

/// <summary>
/// Idempotent subscription handle: safe to Dispose multiple times without side effects.
/// </summary>
public sealed class SubscriptionToken : IDisposable
{
    private Action _unsubscribeAction;
    private bool _isDisposed;

    public static readonly IDisposable Empty = new SubscriptionToken();

    private SubscriptionToken()
    {
        _isDisposed = true;
    }

    public SubscriptionToken(Action unsubscribeAction)
    {
        _unsubscribeAction = unsubscribeAction ?? throw new ArgumentNullException(nameof(unsubscribeAction));
    }

    public void Dispose()
    {
        if (_isDisposed)
        {
            return;
        }

        _isDisposed = true;
        Action action = _unsubscribeAction;
        _unsubscribeAction = null;
        action?.Invoke();
    }
}

/// <summary>
/// Scoped instance-based Event Bus tied to a specific lifecycle (Match, Scene, or UI Screen).
/// Reuses _dispatchBuffer to maintain zero GC allocations on hot-path Publish() calls.
/// </summary>
public sealed class ScopedEventBus<TPayload> : IDisposable
{
    private readonly List<Action<TPayload>> _listeners = new List<Action<TPayload>>();
    private readonly List<Action<TPayload>> _dispatchBuffer = new List<Action<TPayload>>();
    private bool _isDispatching;
    private bool _isDisposed;

    public bool IsDisposed => _isDisposed;
    public int SubscriberCount => _listeners.Count;

    public IDisposable Subscribe(Action<TPayload> handler)
    {
        if (_isDisposed)
        {
            throw new ObjectDisposedException(nameof(ScopedEventBus<TPayload>));
        }

        if (handler == null)
        {
            throw new ArgumentNullException(nameof(handler));
        }

        // Return an Empty token on duplicate subscribe so disposing the redundant token never removes the active subscription
        if (_listeners.Contains(handler))
        {
            return SubscriptionToken.Empty;
        }

        _listeners.Add(handler);
        return new SubscriptionToken(() => Unsubscribe(handler));
    }

    public void Publish(TPayload payload)
    {
        if (_isDisposed)
        {
            throw new ObjectDisposedException(nameof(ScopedEventBus<TPayload>));
        }

        if (_listeners.Count == 0)
        {
            return;
        }

        // Fall back to a local copy only on nested re-entrant Publish() calls inside a listener callback
        if (_isDispatching)
        {
            var nestedSnapshot = _listeners.ToArray();
            for (int i = 0; i < nestedSnapshot.Length; i++)
            {
                if (_isDisposed) break;
                nestedSnapshot[i]?.Invoke(payload);
            }
            return;
        }

        _isDispatching = true;
        _dispatchBuffer.Clear();
        for (int i = 0; i < _listeners.Count; i++)
        {
            _dispatchBuffer.Add(_listeners[i]);
        }

        try
        {
            for (int i = 0; i < _dispatchBuffer.Count; i++)
            {
                if (_isDisposed)
                {
                    break;
                }

                _dispatchBuffer[i]?.Invoke(payload);
            }
        }
        finally
        {
            // Clear buffer immediately after dispatch to avoid holding lingering references
            _dispatchBuffer.Clear();
            _isDispatching = false;
        }
    }

    private void Unsubscribe(Action<TPayload> handler)
    {
        if (_isDisposed || handler == null)
        {
            return;
        }

        _listeners.Remove(handler);
    }

    public void Dispose()
    {
        if (_isDisposed)
        {
            return;
        }

        _isDisposed = true;
        // Sever every strong reference from Publisher to Subscriber
        _listeners.Clear();
        _dispatchBuffer.Clear();
    }
}

/// <summary>
/// Curated static Event Hub strictly for application-wide signals.
/// Uses SubsystemRegistration to clear stale delegates when Domain Reload is disabled.
/// </summary>
public static class GlobalAppEventHub
{
    public static event Action<string> OnAnalyticsMilestoneReached;

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
    public static void ResetOnSubsystemRegistration()
    {
        OnAnalyticsMilestoneReached = null;
    }

    public static void EmitAnalyticsMilestone(string milestoneId)
    {
        if (string.IsNullOrWhiteSpace(milestoneId))
        {
            throw new ArgumentException("Milestone ID cannot be null or empty.", nameof(milestoneId));
        }

        OnAnalyticsMilestoneReached?.Invoke(milestoneId);
    }
}

[TestFixture]
public sealed class ObserverLifecycleTests
{
    private sealed class DummyArenaSubscriber
    {
        public int AccumulatedScore { get; private set; }

        public void OnEnemyDefeated(EnemyDefeatedEvent evt)
        {
            AccumulatedScore += evt.ScoreReward;
        }
    }

    [TearDown]
    public void CleanupStaticHub()
    {
        GlobalAppEventHub.ResetOnSubsystemRegistration();
    }

    [Test]
    public void ScopedEventBus_WhenDisposed_ReleasesSubscriberForGarbageCollection()
    {
        var matchBus = new ScopedEventBus<EnemyDefeatedEvent>();
        WeakReference CreateAndSubscribeWithoutManualUnsubscribe()
        {
            var subscriber = new DummyArenaSubscriber();
            // Intentionally discard the SubscriptionToken to simulate a forgotten unsubscribe
            _ = matchBus.Subscribe(subscriber.OnEnemyDefeated);
            matchBus.Publish(new EnemyDefeatedEvent(101, 50));
            Assert.AreEqual(50, subscriber.AccumulatedScore);
            return new WeakReference(subscriber);
        }

        WeakReference weakRef = CreateAndSubscribeWithoutManualUnsubscribe();

        // While the bus is alive, it retains a strong reference preventing GC collection
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        Assert.AreEqual(1, matchBus.SubscriberCount);
        Assert.IsTrue(weakRef.IsAlive);
        GC.KeepAlive(matchBus);

        // Once the Match owner calls Dispose(), all references are severed
        matchBus.Dispose();
        Assert.IsTrue(matchBus.IsDisposed);
        Assert.AreEqual(0, matchBus.SubscriberCount);

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        // Proves the subscriber is reclaimed by GC even without manual unsubscribe
        Assert.IsFalse(weakRef.IsAlive);
    }

    [Test]
    public void ScopedEventBus_IsolatesConcurrentContexts_AndHandlesDuplicateSubscribeSafely()
    {
        using var matchABus = new ScopedEventBus<EnemyDefeatedEvent>();
        using var matchBBus = new ScopedEventBus<EnemyDefeatedEvent>();

        var subA = new DummyArenaSubscriber();
        var subB = new DummyArenaSubscriber();

        IDisposable tokenA = matchABus.Subscribe(subA.OnEnemyDefeated);
        IDisposable duplicateTokenA = matchABus.Subscribe(subA.OnEnemyDefeated);
        using IDisposable tokenB = matchBBus.Subscribe(subB.OnEnemyDefeated);

        // Duplicate subscribe returns an Empty token, so disposing it does not drop the original registration
        Assert.AreEqual(1, matchABus.SubscriberCount);
        duplicateTokenA.Dispose();
        Assert.AreEqual(1, matchABus.SubscriberCount);

        matchABus.Publish(new EnemyDefeatedEvent(1, 100));
        Assert.AreEqual(100, subA.AccumulatedScore);
        Assert.AreEqual(0, subB.AccumulatedScore); // Match B remains completely isolated from Match A

        // Calling Dispose() repeatedly on tokenA is safe and idempotent
        tokenA.Dispose();
        tokenA.Dispose();
        Assert.AreEqual(0, matchABus.SubscriberCount);
        Assert.AreEqual(1, matchBBus.SubscriberCount);

        matchABus.Publish(new EnemyDefeatedEvent(2, 200));
        Assert.AreEqual(100, subA.AccumulatedScore);
    }

    [Test]
    public void ScopedEventBus_AfterDispose_ThrowsObjectDisposedExceptionOnSubscribeOrPublish()
    {
        var bus = new ScopedEventBus<EnemyDefeatedEvent>();
        var sub = new DummyArenaSubscriber();
        IDisposable token = bus.Subscribe(sub.OnEnemyDefeated);

        bus.Dispose();

        // Disposing the subscription token remains safe after the bus itself is disposed
        Assert.DoesNotThrow(() => token.Dispose());
        Assert.Throws<ObjectDisposedException>(() => bus.Subscribe(sub.OnEnemyDefeated));
        Assert.Throws<ObjectDisposedException>(() => bus.Publish(new EnemyDefeatedEvent(3, 10)));
    }

    [Test]
    public void GlobalAppEventHub_WhenResetOnSubsystemRegistration_ClearsStaleSubscribers()
    {
        int callCount = 0;
        GlobalAppEventHub.OnAnalyticsMilestoneReached += _ => callCount++;

        GlobalAppEventHub.EmitAnalyticsMilestone("tutorial_completed");
        Assert.AreEqual(1, callCount);

        // Simulates Unity Play Mode entry with Domain Reload disabled
        GlobalAppEventHub.ResetOnSubsystemRegistration();

        GlobalAppEventHub.EmitAnalyticsMilestone("chapter_1_clear");
        Assert.AreEqual(1, callCount); // Stale subscriber is not invoked
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Engineering Trade-offs: Static Class vs Instance Class

Neither approach is universally superior for every system. Choosing between a static class and an instance class involves weighing four practical trade-offs:

Trade-off Dimension Static Class / Static Event Hub Instance Class (Scoped Event Bus)
Access & Setup Friction Very convenient: accessible anywhere by class name with zero instantiation Requires explicit instantiation and wiring via Constructor, Context, or DI
Scope & Ownership Clarity No natural scope boundary; easily turns into an untraceable global dumping ground Crystal-clear ownership: each Match, Scene, or UI Screen owns its dedicated bus
Memory Leak Risk (GC Root) High: a single forgotten -= keeps subscribers alive across scenes via static GC Root Much lower: calling Dispose() on scope exit drops all lingering listeners at once
No-Domain-Reload Safety (Editor) High risk of stale delegates unless explicitly reset via [RuntimeInitializeOnLoadMethod] Naturally clean because fresh bus instances are created per session or scene
Test Isolation & Parallelism Hard to isolate; state from one test bleeds into the next if teardown misses a delegate Fully isolated and mockable; supports parallel test runs cleanly
Best Architectural Fit True app-wide signals (Analytics, Global Settings, Connectivity status) Gameplay combat, Match sessions, UI screen flows, multi-context simulations

5. Practical Takeaways for Event Architecture

After fixing cross-scene memory leaks and stale Play Mode callbacks in real Unity projects, three principles keep Observer architectures maintainable at scale:

  1. Do not choose static just to avoid passing references, and do not choose instance just to look architectural: Always anchor the choice on event lifetime. If an event only exists within a match or UI flow, give it a scoped instance with an explicit owner.
  2. Design centralized cleanup instead of relying solely on developer discipline: Everyone knows to write -= in OnDestroy(), yet across tens of thousands of lines of code, someone eventually misses one. Wrapping scoped buses in IDisposable ensures forgotten listeners are dropped cleanly at scope teardown.
  3. Guard every static event against disabled Domain Reload: Any channel kept static must include a reset method marked with [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] so fast Play Mode iteration never executes stale callbacks.

Top comments (0)