TExcelTAD
Home › Unity with C# › ScriptableObject Event Channels

ScriptableObject Event Channels

C# events need the listener to hold a reference to the sender: the health bar must find the player's Health component. Across prefabs and scenes that gets awkward. The coin in Level 3 shouldn't need to find the HUD, which lives in a separate UI scene.

An event channel puts the event itself into a ScriptableObject asset. Senders and listeners both reference the asset (CoinCollected.asset), never each other. This pattern was popularized by Unity's own talks and sample projects (such as Chop Chop and the Open Projects).

The channel

csharp
using System;
using UnityEngine;

[CreateAssetMenu(menuName = "Events/Int Event Channel")]
public class IntEventChannel : ScriptableObject
{
    public event Action<int> Raised;

    public void Raise(int value)
    {
        Raised?.Invoke(value);
    }
}

Create one asset per event: Create > Events > Int Event Channel, named CoinCollected, PlayerDamaged, ScoreChanged.

Sender and listeners

csharp
public class Coin : MonoBehaviour
{
    [SerializeField] int value = 1;
    [SerializeField] IntEventChannel coinCollected;      // drag the CoinCollected asset

    void OnTriggerEnter(Collider other)
    {
        if (!other.CompareTag("Player")) return;
        coinCollected.Raise(value);
        gameObject.SetActive(false);
    }
}

public class CoinCounterView : MonoBehaviour              // lives in the UI scene
{
    [SerializeField] IntEventChannel coinCollected;      // same asset
    [SerializeField] TMPro.TMP_Text label;
    int total;

    void OnEnable()  => coinCollected.Raised += OnCoin;
    void OnDisable() => coinCollected.Raised -= OnCoin;

    void OnCoin(int value) => label.SetText("{0}", total += value);
}

Now the coin prefab works in any scene, the HUD can be tested alone by raising the channel from a debug button, and adding an achievements listener means touching neither the coin nor the HUD.

A model with typed channels

The model builds a tiny channel registry, a sender, three listeners that come and go, and a debug log on each channel. That last part is the pattern's secret weapon: because every event passes through an asset, you can log or inspect them centrally.

csharp · try it yourself
using System;
using System.Collections.Generic;

var coinCollected = new EventChannel<int>("CoinCollected");
var levelFinished = new EventChannel<string>("LevelFinished");

var hud = new CoinHud(coinCollected);
var audio = new CoinAudio(coinCollected);
var achievements = new Achievements(coinCollected, levelFinished);

hud.Enable(); audio.Enable(); achievements.Enable();
coinCollected.Raise(1);
coinCollected.Raise(5);

audio.Disable();                                 // e.g. the audio scene unloaded
coinCollected.Raise(1);
levelFinished.Raise("Cave");

Console.WriteLine("-- channel log --");
foreach (var line in EventChannelLog.Lines) Console.WriteLine(line);

static class EventChannelLog { public static readonly List<string> Lines = new(); }

class EventChannel<T>
{
    readonly string name;
    event Action<T>? Raised;
    int listeners;
    public EventChannel(string n) => name = n;
    public void Subscribe(Action<T> a) { Raised += a; listeners++; }
    public void Unsubscribe(Action<T> a) { Raised -= a; listeners--; }
    public void Raise(T value)
    {
        EventChannelLog.Lines.Add(
quot;{name}({value}) -> {listeners} listener(s)"); Raised?.Invoke(value); } } class CoinHud { readonly EventChannel<int> ch; int total; public CoinHud(EventChannel<int> c) => ch = c; public void Enable() => ch.Subscribe(OnCoin); void OnCoin(int v) { total += v; Console.WriteLine(
quot;HUD: coins {total}"); } } class CoinAudio { readonly EventChannel<int> ch; public CoinAudio(EventChannel<int> c) => ch = c; public void Enable() => ch.Subscribe(OnCoin); public void Disable() => ch.Unsubscribe(OnCoin); void OnCoin(int v) => Console.WriteLine(v >= 5 ? "Audio: big chime" : "Audio: ding"); } class Achievements { readonly EventChannel<int> coins; readonly EventChannel<string> levels; int total; public Achievements(EventChannel<int> c, EventChannel<string> l) { coins = c; levels = l; } public void Enable() { coins.Subscribe(OnCoin); levels.Subscribe(OnLevel); } void OnCoin(int v) { total += v; if (total >= 7) Console.WriteLine("Achievement: Coin Hoarder"); } void OnLevel(string level) => Console.WriteLine(
quot;Achievement check for {level}: {total} coins"); }
HUD: coins 1
Audio: ding
HUD: coins 6
Audio: big chime
HUD: coins 7
Achievement: Coin Hoarder
Achievement check for Cave: 7 coins
-- channel log --
CoinCollected(1) -> 3 listener(s)
CoinCollected(5) -> 3 listener(s)
CoinCollected(1) -> 2 listener(s)
LevelFinished(Cave) -> 1 listener(s)

Trade-offs

Pro Con
no references between senders and listeners "who raises this?" needs a search for the asset (Rider's and Unity's Find References In Scene help)
works across scenes and prefabs many small assets to name and organize
easy to test and debug centrally event order between listeners is subscription order, not explicit
designers can wire things without code channels still hold strong references: unsubscribe in OnDisable

A related pattern is the runtime set: a ScriptableObject holding a List<Enemy> that enemies add themselves to in OnEnable and remove in OnDisable. Systems that need "all enemies" read the set instead of calling FindObjectsByType every frame.

Note: Event channels hold subscriptions in a ScriptableObject, which outlives scenes. With domain reload disabled (Enter Play Mode Options), stale subscribers from the last Play session can survive. Clear them in the channel's OnDisable, or make sure every listener unsubscribes.

Test yourself

What do the sender and listeners of a ScriptableObject event channel reference?

  1. Each other directly
  2. The shared channel asset
  3. A static singleton
  4. The scene file

What is a 'runtime set'?

  1. A Unity build setting
  2. A ScriptableObject list that objects add and remove themselves from
  3. A set of input bindings
  4. A coroutine pool

Which is a real downside of event channels?

  1. They can't cross scene boundaries
  2. It's harder to see who raises or listens to an event without tooling
  3. They allocate memory per frame
  4. They only work in the editor