TExcelTAD
Home › Unity with C# › C# Events & UnityEvents

C# Events & UnityEvents

When the player's health changes, the health bar, the damage flash, the audio and the achievements system all need to know. If PlayerHealth called each of them directly, it would depend on all of them. Events reverse that: PlayerHealth announces "health changed", and anyone interested subscribes.

Unity code uses two kinds:

C# event Action<T> UnityEvent<T>
Wired up in code (+= / -=) the Inspector (drag an object, pick a method) or code (AddListener)
Speed fast slower (reflection-based persistent calls)
Good for system-to-system code designer-facing hooks: buttons, triggers, "on open play this sound"
Risk forgetting -= hidden wiring that's hard to search for

C# events in a component

csharp
using System;
using UnityEngine;
using UnityEngine.Events;

public class Health : MonoBehaviour
{
    [SerializeField] int max = 100;
    int current;

    public event Action<int, int> Changed;     // (current, max), for code
    public event Action Died;
    [SerializeField] UnityEvent onDied;        // for designers: hook up effects in the Inspector

    void Awake() => current = max;

    public void TakeDamage(int amount)
    {
        if (current <= 0) return;
        current = Mathf.Max(0, current - amount);
        Changed?.Invoke(current, max);         // ?. is fine here: delegates are plain C# objects
        if (current == 0) { Died?.Invoke(); onDied.Invoke(); }
    }
}

public class HealthBar : MonoBehaviour
{
    [SerializeField] Health target;
    [SerializeField] UnityEngine.UI.Image fill;

    void OnEnable()  => target.Changed += Refresh;    // subscribe when enabled
    void OnDisable() => target.Changed -= Refresh;    // ALWAYS unsubscribe in the mirror method

    void Refresh(int current, int max) => fill.fillAmount = (float)current / max;
}

OnEnable/OnDisable is the standard pair: a disabled health bar stops listening, and destroying it runs OnDisable first, so it unsubscribes automatically.

The leak you get without -=

An event holds a strong reference to every subscriber. If a short-lived object subscribes to a long-lived one (a static event, a game manager) and never unsubscribes, the destroyed object keeps receiving calls. In Unity that typically shows up as a MissingReferenceException from an object that "doesn't exist anymore". The model:

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

var bus = new ScoreSystem();
var hud = new Hud("HUD");
var popup = new Popup("Popup");

hud.OnEnable(bus);
popup.OnEnable(bus);
bus.Add(10);

popup.Destroy(bus, unsubscribe: false);         // the bug: no -= in OnDisable
bus.Add(5);

Console.WriteLine(
quot;subscribers still attached: {bus.SubscriberCount}"); class ScoreSystem { public event Action<int>? ScoreChanged; int score; public int SubscriberCount => ScoreChanged?.GetInvocationList().Length ?? 0; public void Add(int points) { score += points; Console.WriteLine(
quot;score -> {score}"); ScoreChanged?.Invoke(score); } } class Hud { readonly string name; public Hud(string n) => name = n; public void OnEnable(ScoreSystem s) => s.ScoreChanged += Show; void Show(int score) => Console.WriteLine(
quot; {name}: shows {score}"); } class Popup { readonly string name; bool destroyed; public Popup(string n) => name = n; public void OnEnable(ScoreSystem s) => s.ScoreChanged += Show; public void Destroy(ScoreSystem s, bool unsubscribe) { if (unsubscribe) s.ScoreChanged -= Show; destroyed = true; Console.WriteLine(
quot;{name} destroyed"); } void Show(int score) { if (destroyed) { Console.WriteLine(
quot; {name}: MissingReferenceException (destroyed but still subscribed)"); return; } Console.WriteLine(
quot; {name}: +{score}!"); } }
score -> 10
  HUD: shows 10
  Popup: +10!
Popup destroyed
score -> 15
  HUD: shows 15
  Popup: MissingReferenceException (destroyed but still subscribed)
subscribers still attached: 2

Change unsubscribe: false to true and the third subscriber line disappears. Static events (public static event Action PlayerDied) make the leak worse: they survive scene loads, and with Enter Play Mode Options (domain reload disabled) they even survive between Play sessions. Reset static state with [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] if you use that option.

UnityEvents from code

csharp
[SerializeField] UnityEngine.UI.Button playButton;

void OnEnable()  => playButton.onClick.AddListener(StartGame);
void OnDisable() => playButton.onClick.RemoveListener(StartGame);

Listeners added in code are not shown in the Inspector, and RemoveAllListeners() only removes code-added ones, not the persistent ones set up in the Inspector.

For decoupling across scenes and prefabs (a pickup in the level talking to a HUD in another scene), Unity projects often put the event itself into an asset. That is the ScriptableObject event channel pattern.

Test yourself

Where should a MonoBehaviour subscribe to and unsubscribe from a C# event?

  1. Awake and Start
  2. OnEnable and OnDisable
  3. Update and LateUpdate
  4. Start and OnApplicationQuit

Why can a destroyed object still receive event calls?

  1. Events are copied when invoked
  2. The event's delegate holds a strong reference to the subscriber until it unsubscribes
  3. Unity re-creates destroyed objects
  4. Events are always static

When is a UnityEvent a better choice than a C# event?

  1. Hot code paths called thousands of times per frame
  2. Designer-facing hooks wired in the Inspector
  3. Static global events
  4. Never