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.
Code
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);
}
}
}using System;
using System.Collections.Generic;
using UnityEngine;
namespace Patterns.GameProgramming.EventBus
{
/// <summary>
/// A global, typed publish/subscribe hub. Publishers and subscribers only
/// share event types; neither side holds a reference to the other.
/// </summary>
public static class EventBus
{
private static readonly Dictionary<Type, Delegate> handlers = new();
public static void Subscribe<T>(Action<T> handler) where T : struct
{
handlers.TryGetValue(typeof(T), out Delegate existing);
handlers[typeof(T)] = Delegate.Combine(existing, handler);
}
public static void Unsubscribe<T>(Action<T> handler) where T : struct
{
if (!handlers.TryGetValue(typeof(T), out Delegate existing)) return;
Delegate remaining = Delegate.Remove(existing, handler);
if (remaining == null) handlers.Remove(typeof(T));
else handlers[typeof(T)] = remaining;
}
public static void Publish<T>(T evt) where T : struct
{
// Only handlers registered for exactly this type are called.
if (handlers.TryGetValue(typeof(T), out Delegate d))
((Action<T>)d).Invoke(evt);
}
// Static state survives "Enter Play Mode" when domain reload is disabled.
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void ResetStatics() => handlers.Clear();
}
}using UnityEngine;
namespace Patterns.GameProgramming.EventBus
{
// Event types are plain structs: the type is the "channel",
// the fields are the payload. Publishing one allocates nothing.
public readonly struct PlayerDied
{
public readonly Vector3 Position;
public PlayerDied(Vector3 position) => Position = position;
}
public readonly struct CoinCollected
{
public readonly int Amount;
public readonly int Total;
public CoinCollected(int amount, int total)
{
Amount = amount;
Total = total;
}
}
public readonly struct ItemPurchased
{
public readonly string ItemId;
public readonly int Price;
public ItemPurchased(string itemId, int price)
{
ItemId = itemId;
Price = price;
}
}
}using TMPro;
using UnityEngine;
namespace Patterns.GameProgramming.EventBus
{
/// <summary>
/// A subscriber. It never references the player or the shop; it only
/// knows the event types it cares about.
/// </summary>
public class CoinHud : MonoBehaviour
{
[SerializeField] private TMP_Text coinLabel;
[SerializeField] private GameObject deathBanner;
private void OnEnable()
{
EventBus.Subscribe<CoinCollected>(OnCoinCollected);
EventBus.Subscribe<PlayerDied>(OnPlayerDied);
}
// Without this, the static bus keeps calling a destroyed HUD after the
// scene unloads (MissingReferenceException, and the HUD never gets collected).
private void OnDisable()
{
EventBus.Unsubscribe<CoinCollected>(OnCoinCollected);
EventBus.Unsubscribe<PlayerDied>(OnPlayerDied);
}
private void OnCoinCollected(CoinCollected e) => coinLabel.text = e.Total.ToString();
private void OnPlayerDied(PlayerDied e) => deathBanner.SetActive(true);
}
}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
playerandshopfields and bothFindAnyObjectByTypecalls are gone. - The tracker subscribes with
EventBus.Subscribe<CoinCollected>,EventBus.Subscribe<PlayerDied>andEventBus.Subscribe<ItemPurchased>, and unsubscribes inOnDisable. - Handlers receive typed structs (
CoinCollected e) instead of loose parameters, so the payload is named and can grow without breaking signatures.
using UnityEngine;
namespace Patterns.GameProgramming.EventBus
{
/// <summary>
/// Without an event bus: to hear about coins, deaths and purchases the
/// tracker has to find and hold the objects that raise them.
/// </summary>
public class AchievementTracker : MonoBehaviour
{
[SerializeField] private int coinGoal = 100;
private Player player;
private Shop shop;
private int coinsSeen;
private void OnEnable()
{
// Throws NullReferenceException in any scene without a Player or a Shop (menu, test scene).
player = FindAnyObjectByType<Player>();
shop = FindAnyObjectByType<Shop>();
player.CoinCollected += OnCoinCollected;
player.Died += OnPlayerDied;
shop.ItemPurchased += OnItemPurchased;
}
private void OnDisable()
{
player.CoinCollected -= OnCoinCollected;
player.Died -= OnPlayerDied;
shop.ItemPurchased -= OnItemPurchased;
}
private void OnCoinCollected(int amount)
{
coinsSeen += amount;
if (coinsSeen >= coinGoal) Unlock("coin_hoarder");
}
private void OnPlayerDied() => Unlock("first_death");
private void OnItemPurchased(string itemId, int price) => Unlock("first_purchase");
private void Unlock(string id) => Debug.Log($"Achievement unlocked: {id}");
}
}using UnityEngine;
namespace Patterns.GameProgramming.EventBus
{
/// <summary>
/// With an event bus: the tracker subscribes to event types. It does not
/// know, or care, which objects publish them.
/// </summary>
public class AchievementTracker : MonoBehaviour
{
[SerializeField] private int coinGoal = 100;
private int coinsSeen;
private void OnEnable()
{
EventBus.Subscribe<CoinCollected>(OnCoinCollected);
EventBus.Subscribe<PlayerDied>(OnPlayerDied);
EventBus.Subscribe<ItemPurchased>(OnItemPurchased);
}
private void OnDisable()
{
EventBus.Unsubscribe<CoinCollected>(OnCoinCollected);
EventBus.Unsubscribe<PlayerDied>(OnPlayerDied);
EventBus.Unsubscribe<ItemPurchased>(OnItemPurchased);
}
private void OnCoinCollected(CoinCollected e)
{
coinsSeen += e.Amount;
if (coinsSeen >= coinGoal) Unlock("coin_hoarder");
}
private void OnPlayerDied(PlayerDied e) => Unlock("first_death");
private void OnItemPurchased(ItemPurchased e) => Unlock("first_purchase");
private void Unlock(string id) => Debug.Log($"Achievement unlocked: {id}");
}
}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
- 01Always pair
SubscribeinOnEnablewithUnsubscribeinOnDisable; the bus is static and outlives every scene. - 02Clear the dictionary from a
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]method, or stale handlers survive between play sessions when domain reload is disabled. - 03Use
readonly structevents andAction<T>handlers so publishing does not allocate. - 04If you need designer-facing, Inspector-wired events, ScriptableObject event channels give the same decoupling with visible references.
- 05If a handler needs to publish another event, consider an Event Queue instead, so nested publishes run in a predictable order.