C# Events vs UnityEvent in Unity: Delegates, Action and UnityAction

Illustration of a broadcast node sending signals to listener nodes

When the player takes damage, the health bar should shrink, the screen should flash, a sound should play and maybe an achievement should unlock. If PlayerHealth calls all of those directly, it has to know about every one of them, and every new feature means editing it again. Events fix that: the player just announces “I took damage”, and whoever cares listens. Unity gives you three ways to do it: C# delegates and events, Action and Func, and UnityEvent. This guide explains each, when to use which, and how to avoid the memory leaks and errors that events cause when used carelessly.

The Problem Events Solve

Here’s the version without events:

public class PlayerHealth : MonoBehaviour
{
    public HealthBar healthBar;
    public ScreenFlash screenFlash;
    public AudioSource hurtSound;
    public AchievementManager achievements;

    public void TakeDamage(int amount)
    {
        health -= amount;
        healthBar.SetValue(health);
        screenFlash.Flash();
        hurtSound.Play();
        achievements.OnPlayerDamaged();
        // ...every new feature adds another line here
    }
}

PlayerHealth depends on four other systems. You can’t reuse it in another project, test it alone, or remove the screen flash without editing it. With an event, PlayerHealth only knows about itself:

public class PlayerHealth : MonoBehaviour
{
    public event System.Action<int, int> Damaged;   // (current, max)

    [SerializeField] int max = 100;
    int health;

    void Awake() => health = max;

    public void TakeDamage(int amount)
    {
        health = Mathf.Max(health - amount, 0);
        Damaged?.Invoke(health, max);
    }
}

The health bar, flash, sound and achievements each subscribe to Damaged themselves. Adding or removing one doesn’t touch PlayerHealth.

Delegates in One Minute

A delegate is a type that holds a reference to one or more methods with a specific signature. Events are built on them.

public delegate void ScoreChanged(int newScore);   // the signature

ScoreChanged onScore;              // a variable that can hold methods
onScore += UpdateScoreText;        // add a method
onScore += CheckHighScore;         // add another
onScore?.Invoke(150);              // calls both, in order

void UpdateScoreText(int s) { /* ... */ }
void CheckHighScore(int s) { /* ... */ }

+= adds a method, -= removes it, and ?.Invoke calls them all, safely doing nothing if there are none.

Action and Func

Declaring a delegate type for every event gets tedious. .NET includes ready-made generic ones:

  • Action: no parameters, no return value.
  • Action<T1, T2, ...>: up to 16 parameters, no return value. Action<int> is the same shape as the ScoreChanged delegate above.
  • Func<..., TResult>: returns a value. Func<int, bool> takes an int and returns a bool. Used more for callbacks and queries than events.

In Unity code, Action and Action<T> are the most common choice for events. Custom delegate types are still useful when you want named parameters to show up in IntelliSense.

The event Keyword

You could expose a public Action field, but then any other script could do player.Damaged = null (wiping out every subscriber) or call player.Damaged.Invoke() (faking damage). Adding the event keyword restricts outside code to only += and -=. Only the class that declares the event can invoke it.

public event Action Died;        // outsiders can only subscribe/unsubscribe
public Action DiedField;         // outsiders can overwrite or invoke it. Avoid.

A listener subscribes in OnEnable and unsubscribes in OnDisable:

public class HealthBar : MonoBehaviour
{
    [SerializeField] PlayerHealth player;
    [SerializeField] UnityEngine.UI.Image fill;

    void OnEnable()  => player.Damaged += OnDamaged;
    void OnDisable() => player.Damaged -= OnDamaged;

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

UnityEvent

UnityEvent is Unity’s own event type, and it’s serializable. That means it shows up in the Inspector, where you can drag in objects and pick methods to call, exactly like a Button’s On Click () list (which is itself a UnityEvent).

using UnityEngine;
using UnityEngine.Events;

public class PressurePlate : MonoBehaviour
{
    public UnityEvent Pressed;
    public UnityEvent<float> WeightChanged;   // generic version with a parameter

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player")) Pressed.Invoke();
    }
}

Now a designer can make the plate open a door, play a sound and start a cutscene without writing code, by wiring those in the Inspector. Code can still subscribe with Pressed.AddListener(Method) and RemoveListener(Method).

Inspector listeners vs code listeners

A UnityEvent keeps two separate lists, and most UnityEvent confusion comes from mixing them up:

  • Persistent listeners are the rows you add with the + button in the Inspector. They’re saved in the scene or prefab.
  • Runtime listeners are the ones code adds with AddListener. They exist only while the game runs and never appear in the Inspector.

Invoke() calls both. RemoveListener and RemoveAllListeners() only touch the runtime list, so calling button.onClick.RemoveAllListeners() will not stop a method that was wired in the Inspector. To switch an Inspector row off from code, use its index:

for (int i = 0; i < Pressed.GetPersistentEventCount(); i++)
{
    Debug.Log($"{i}: {Pressed.GetPersistentTarget(i)}.{Pressed.GetPersistentMethodName(i)}");
}
Pressed.SetPersistentListenerState(0, UnityEventCallState.Off);

Each Inspector row also has a small dropdown: Runtime Only (the default), Editor And Runtime, or Off. A row set to Off is the classic “I wired it up and nothing happens” cause.

The function picker has two sections. Under Static Parameters, you type the argument into the row itself (for example, GameObject.SetActive with the box ticked). Under Dynamic, the method receives whatever value the event is invoked with, which is what you want for a UnityEvent<float> driven by a slider. A UnityEvent can carry up to four values, such as UnityEvent<int, bool>. Since Unity 2020.1 these generic fields serialize directly; older tutorials declare a [Serializable] subclass like class FloatEvent : UnityEvent<float> {}, which still works but isn’t required in Unity 6.

๐Ÿ“ Consistent names for events and handlers

Is it Died, OnDied or onDeath? Mixed event naming makes code hard to search. Our free reference lists the common Unity C# naming conventions, events and handlers included.

Open the Unity Naming Convention Reference →

C# Events vs UnityEvent

C# event (Action) UnityEvent
Wire up in the Inspector No Yes
Performance Faster Slower to invoke, allocates when adding listeners
Protection from outside invoke Yes, with event No, anyone can call Invoke
Visible in code where it’s used Yes, find references works Inspector links are invisible to code search
Good for System-to-system communication Designer-facing hooks, one-off level logic

A practical rule: use C# events for programmer-to-programmer communication between systems, and UnityEvents for designer-facing hooks on reusable components (triggers, buttons, interactables). The performance difference only matters for events fired many times per frame.

The invisible-reference problem is real: if a method is only called from a UnityEvent wired in a scene, “Find All References” won’t find it, and someone may delete it as unused. Name those methods clearly, or keep them in components meant for Inspector wiring.

Static Events and Event Buses

Sometimes the listener can’t easily get a reference to the sender, like an achievement system that wants to know whenever any enemy dies. A static event solves that:

public class Enemy : MonoBehaviour
{
    public static event Action<Enemy> AnyDied;

    public void Die()
    {
        AnyDied?.Invoke(this);
        Destroy(gameObject);
    }
}

public class KillCounter : MonoBehaviour
{
    int kills;
    void OnEnable()  => Enemy.AnyDied += Count;
    void OnDisable() => Enemy.AnyDied -= Count;
    void Count(Enemy e) => kills++;
}

Static events live for the whole application, so forgetting to unsubscribe is even more dangerous with them. If you use Enter Play Mode Options with domain reload disabled, static events also keep their subscribers between play sessions. Clear them with a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] method that sets them to null.

Instance event or static event?

Ask whether the listener cares about one specific sender or any sender. A floating health bar above an enemy cares about its own enemy, so it subscribes to that enemy’s instance event through a reference (often set when the bar is spawned). If you made Damaged static instead, every health bar in the scene would react to every hit. A kill counter or achievement tracker cares about any enemy, so a static event fits, and the event should pass the sender (Action<Enemy>) so listeners can tell which one it was.

For larger projects, ScriptableObject event channels are another option: the event lives in an asset that both sides reference. See our ScriptableObjects guide for that pattern.

Sending More Data With an Event

Once an event needs four or five values, Action<int, int, Vector3, bool, GameObject> becomes hard to read, and adding a sixth value breaks every subscriber. Bundle the data in a small struct instead:

public readonly struct DamageInfo
{
    public readonly int Amount;
    public readonly Vector3 HitPoint;
    public readonly GameObject Source;
    public readonly bool IsCritical;

    public DamageInfo(int amount, Vector3 hitPoint, GameObject source, bool isCritical)
    {
        Amount = amount; HitPoint = hitPoint; Source = source; IsCritical = isCritical;
    }
}

public event Action<DamageInfo> Damaged;
// raise:  Damaged?.Invoke(new DamageInfo(12, hit.point, gameObject, false));
// handle: void OnDamaged(DamageInfo info) { if (info.IsCritical) ShakeCamera(); }

Adding a field later doesn’t change any subscriber’s signature, and a struct doesn’t create garbage each time you raise the event. You may also see the standard .NET style, EventHandler<T> with a (object sender, T args) signature. It works fine in Unity; most Unity code skips the sender argument and puts the sender in the data when it’s needed.

Rules That Prevent Bugs

  1. Always unsubscribe. Subscribe in OnEnable, unsubscribe in OnDisable. A destroyed object that’s still subscribed will be called, and accessing its components throws a MissingReferenceException. It also keeps the object from being garbage collected.
  2. Don’t subscribe with lambdas you need to remove. player.Died += () => Show(); can’t be removed with -= and a new lambda, because it’s a different delegate instance. Use a named method, or store the lambda in a field.
  3. Invoke with ?.: Died?.Invoke(). An event with no subscribers is null, and calling it directly throws a NullReferenceException.
  4. Don’t rely on subscriber order. Subscribers run in the order they subscribed, which depends on script execution order. If B must run after A, have A raise its own event.
  5. Be careful changing subscriptions inside a handler. A handler that destroys other listeners or subscribes new ones during an Invoke can cause confusing results.
  6. Remember that C# events ignore enabled. A disabled component that is still subscribed still gets called. That’s another reason to unsubscribe in OnDisable: it makes “disabled” actually mean “not listening”. It also matters for pooled objects, which are deactivated rather than destroyed (see our object pooling guide).
  7. One exception stops the rest. When a C# event calls its subscribers and one of them throws, the subscribers after it are never called for that event. If a later system mysteriously stops reacting, look for an earlier error in the Console first.

Troubleshooting

MissingReferenceException: The object of type ‘X’ has been destroyed but you are still trying to access it

A destroyed listener is still subscribed. Add the matching -= in OnDisable (or RemoveListener for UnityEvents).

NullReferenceException when raising an event

No one is subscribed, so the delegate is null. Use ?.Invoke(). If the exception is inside a handler, the problem is in that handler.

The handler runs twice

The listener subscribed twice, usually once in Awake/Start and again in OnEnable, or OnEnable ran twice without an OnDisable removing it. Keep subscribe/unsubscribe in one matching pair.

The UnityEvent method isn’t listed in the Inspector

Inspector wiring only shows public methods that return void and have zero or one parameter of a supported type (int, float, string, bool, Object). For a UnityEvent<T>, choose the method under the Dynamic section to receive the event’s value.

“The event can only appear on the left hand side of += or -=”

You tried to invoke or assign an event from outside its class. That’s the event keyword protecting it. Add a public method on the owning class that raises it, if outside code really should trigger it.

The handler never runs at all

Work through these in order:

  1. Wrong instance. If the listener’s field points at the prefab asset in the Project window instead of the object in the scene, it subscribed to an object that never raises anything. Drag the scene instance into the field, or assign the reference when you spawn it.
  2. The listener never subscribed. OnEnable only runs on active objects. A UI panel that starts inactive won’t subscribe until it’s switched on, so it misses everything raised before that.
  3. It subscribed too late. If the sender raises the event in its own Start and the listener subscribes in a later Start, the first call is missed. Have listeners read the current value when they subscribe (for example OnDamaged(player.Health, player.Max) right after +=), rather than waiting for the next change.
  4. A breakpoint or Debug.Log at the Invoke line tells you which side is broken: if the log fires, the sender is fine and the problem is the subscription.

Every button in a loop passes the same index

This is a lambda capture bug:

for (int i = 0; i < buttons.Length; i++)
{
    int index = i;   // copy for this iteration
    buttons[i].onClick.AddListener(() => SelectSlot(index));
}

Without the index copy, every lambda shares the same i variable, which equals buttons.Length once the loop finishes, so every button reports the last value or throws an out-of-range error. A foreach loop gives each iteration its own variable, so it doesn’t have this problem.

An Inspector-wired method shows as “Missing” after a rename

Persistent listeners store the method by name. Renaming the method, or changing its parameters, breaks the link without a compile error, and the row then shows the method as missing. Pick the method again in each affected row. This is the main reason to keep UnityEvent wiring for a small number of designer-facing hooks.

Still Broken? Check These

  • The listener references the scene instance, not the prefab asset.
  • The listener’s GameObject is active, so OnEnable actually ran.
  • Every += in OnEnable has a matching -= in OnDisable with the same named method.
  • Events are raised with ?.Invoke(), and the Console shows no earlier exception from another subscriber.
  • Inspector rows are not set to Off, and the method is picked from the Dynamic section when it should receive the event’s value.
  • Code that calls RemoveAllListeners() isn’t expected to remove Inspector rows; it can’t.
  • Lambdas created in for loops copy the loop variable first.
  • Static events are cleared on startup if domain reload is turned off.

FAQ

What’s the difference between a delegate and an event in C#?

A delegate is a type that references methods. An event is a delegate field with the event keyword, which only lets other classes subscribe and unsubscribe, not invoke or overwrite it.

Should I use UnityEvent or C# events?

C# events for code-to-code communication, since they’re faster and protected. UnityEvent when designers need to wire responses in the Inspector.

What is Action in Unity?

System.Action is a built-in .NET delegate type for methods with no return value. Action<T> takes parameters. It’s the usual type for C# events in Unity.

Do I need to unsubscribe from events?

Yes. Unsubscribe in OnDisable. Otherwise destroyed objects stay subscribed, which causes MissingReferenceExceptions and memory leaks.

Are UnityEvents slow?

Slower than C# events, but fine for things that happen occasionally, like button clicks and triggers. Avoid them for events fired many times per frame.

How do I pass a value with a UnityEvent?

Use the generic UnityEvent<T>, invoke it with a value, and pick the listener method from the Dynamic section in the Inspector.

What is the difference between UnityAction and UnityEvent?

UnityAction is just a delegate type from UnityEngine.Events, like System.Action. UnityEvent is a serializable event object: it shows in the Inspector so listeners can be wired there, and you add code listeners with AddListener, which takes a UnityAction.

How do I write an event with System.Action in Unity?

Declare public static event Action<int> ScoreChanged; (add using System;), raise it with ScoreChanged?.Invoke(score);, subscribe in OnEnable with ScoreChanged += OnScoreChanged; and unsubscribe with -= in OnDisable.

Does RemoveAllListeners remove Inspector listeners?

No. It only removes listeners added from code with AddListener. Listeners wired in the Inspector stay; switch one off with SetPersistentListenerState or remove it in the Inspector.

Why does my event still call a disabled object?

C# events don’t check whether a component is enabled. Unsubscribe in OnDisable so a disabled object stops receiving events.

Comments

One response to “C# Events vs UnityEvent in Unity: Delegates, Action and UnityAction”

  1. […] your weapon script, raise one event like OnHit(HitInfo) and let a feedback component react. Our C# events guide shows the […]

Leave a Reply

Your email address will not be published. Required fields are marked *