←All patterns
Game Programming

Event Bus

A global, typed publish/subscribe hub where publishers and subscribers share only event types, never references to each other.

What Is It?

An Event Bus is one well-known place where anyone can publish an event and anyone can subscribe to a type of event. The player calls EventBus.Publish(new CoinCollected(1, total)); the HUD, the audio system and the achievement tracker each called EventBus.Subscribe<CoinCollected>(handler) earlier. Nobody holds a reference to anybody else.

Compare it with its neighbours. With Observer, a listener must reach the subject first (player.HealthChanged += ...), so it still depends on PlayerHealth. A Mediator knows its colleagues and contains coordination rules. A Service Locator hands out services you then call directly. The bus does none of this: it routes event values by type and holds no game logic at all.

In C# a compact implementation is a static Dictionary<Type, Delegate>: Subscribe<T> combines a handler into the delegate stored under typeof(T), and Publish<T> invokes it. Events are small readonly structs such as PlayerDied or CoinCollected, so the type itself is the channel and the fields are the payload. Delivery is synchronous: every subscriber runs inside the Publish call.

When Is It Used?

Use it for game-wide notifications that many unrelated systems care about and that can come from many places: player died, coin collected, level completed, item purchased, settings changed.

It is especially useful when publishers and subscribers live in different scenes or are created at different times, so wiring them directly would require FindObjectOfType calls or singletons.

Avoid it for local relationships (a button and its panel, a turret and its target) and for request/response. A global bus used for everything turns into invisible spaghetti where any script can trigger anything.

Interactive Demo

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

Event Bus Pattern
published0delivered0errors0
Player
publisher
Enemy
publisher
Shop
publisher
static EventBus
PlayerDied4
CoinCollected3
ItemPurchased3
UI
subscribed
Audio
subscribed
Achieve
subscribed
Analytics
subscribed
Gameplay.unity
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ EventBus ›PlayerWallet.cs
using UnityEngine;

namespace Patterns.GameProgramming.EventBus
{
    /// <summary>
    /// A publisher. It announces what happened and moves on; it has no idea
    /// whether the HUD, audio or analytics are even loaded.
    /// </summary>
    public class PlayerWallet : MonoBehaviour
    {
        [SerializeField] private int coins;

        private void OnTriggerEnter(Collider other)
        {
            if (!other.CompareTag("Coin")) return;

            coins++;
            other.gameObject.SetActive(false);
            EventBus.Publish(new CoinCollected(1, coins));
        }

        public void Kill()
        {
            EventBus.Publish(new PlayerDied(transform.position));
            gameObject.SetActive(false);
        }
    }
}
4 files · namespace Patterns.Game Programming.EventBusC# · UTF-8 · LF

Before & After

Real-world smell: an achievement tracker that finds the player and the shop to subscribe. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

AchievementTracker calls FindAnyObjectByType<Player>() and FindAnyObjectByType<Shop>() in OnEnable, then subscribes to their C# events. The HUD and the audio system do the same thing with their own copies of those references.

Every listener now depends on every publisher. Load the tracker in a menu scene and player is null; add a ChestOpened source and every listener needs a new field and a new search.

✓ What changed

  • The player and shop fields and both FindAnyObjectByType calls are gone.
  • The tracker subscribes with EventBus.Subscribe<CoinCollected>, EventBus.Subscribe<PlayerDied> and EventBus.Subscribe<ItemPurchased>, and unsubscribes in OnDisable.
  • Handlers receive typed structs (CoinCollected e) instead of loose parameters, so the payload is named and can grow without breaking signatures.
AchievementTracker.Before.cs → AchievementTracker.After.cs+12/−18
11 using UnityEngine;
22
33 namespace Patterns.GameProgramming.EventBus
44 {
55 /// <summary>
6− /// Without an event bus: to hear about coins, deaths and purchases the
7− /// tracker has to find and hold the objects that raise them.
6+ /// With an event bus: the tracker subscribes to event types. It does not
7+ /// know, or care, which objects publish them.
88 /// </summary>
99 public class AchievementTracker : MonoBehaviour
1010 {
1111 [SerializeField] private int coinGoal = 100;
1212
13− private Player player;
14− private Shop shop;
1513 private int coinsSeen;
1614
1715 private void OnEnable()
1816 {
19− // Throws NullReferenceException in any scene without a Player or a Shop (menu, test scene).
20− player = FindAnyObjectByType<Player>();
21− shop = FindAnyObjectByType<Shop>();
22−
23− player.CoinCollected += OnCoinCollected;
24− player.Died += OnPlayerDied;
25− shop.ItemPurchased += OnItemPurchased;
17+ EventBus.Subscribe<CoinCollected>(OnCoinCollected);
18+ EventBus.Subscribe<PlayerDied>(OnPlayerDied);
19+ EventBus.Subscribe<ItemPurchased>(OnItemPurchased);
2620 }
2721
2822 private void OnDisable()
2923 {
30− player.CoinCollected -= OnCoinCollected;
31− player.Died -= OnPlayerDied;
32− shop.ItemPurchased -= OnItemPurchased;
24+ EventBus.Unsubscribe<CoinCollected>(OnCoinCollected);
25+ EventBus.Unsubscribe<PlayerDied>(OnPlayerDied);
26+ EventBus.Unsubscribe<ItemPurchased>(OnItemPurchased);
3327 }
3428
35− private void OnCoinCollected(int amount)
29+ private void OnCoinCollected(CoinCollected e)
3630 {
37− coinsSeen += amount;
31+ coinsSeen += e.Amount;
3832 if (coinsSeen >= coinGoal) Unlock("coin_hoarder");
3933 }
4034
41− private void OnPlayerDied() => Unlock("first_death");
35+ private void OnPlayerDied(PlayerDied e) => Unlock("first_death");
4236
43− private void OnItemPurchased(string itemId, int price) => Unlock("first_purchase");
37+ private void OnItemPurchased(ItemPurchased e) => Unlock("first_purchase");
4438
4539 private void Unlock(string id) => Debug.Log($"Achievement unlocked: {id}");
4640 }
4741 }

Advantages & Disadvantages

+ Advantages

  • Publishers and subscribers are fully decoupled: adding an analytics system means one new subscriber and zero edits elsewhere.
  • Typed events give compile-time safety and a natural place for payload data, with no string keys to mistype.
  • Works across scenes and prefabs, because nothing is wired through the hierarchy.

− Disadvantages

  • It is global state: a subscriber that forgets to unsubscribe stays in the static dictionary after its scene unloads, a classic leak that ends in MissingReferenceException.
  • Control flow is hidden; “who reacts to PlayerDied?” needs a search instead of a click.
  • Overuse couples everything to the bus and to a growing list of event types, and subscriber call order is not something to rely on.

Tips

  1. 01Always pair Subscribe in OnEnable with Unsubscribe in OnDisable; the bus is static and outlives every scene.
  2. 02Clear the dictionary from a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] method, or stale handlers survive between play sessions when domain reload is disabled.
  3. 03Use readonly struct events and Action<T> handlers so publishing does not allocate.
  4. 04If you need designer-facing, Inspector-wired events, ScriptableObject event channels give the same decoupling with visible references.
  5. 05If a handler needs to publish another event, consider an Event Queue instead, so nested publishes run in a predictable order.