Unity Action

In by John FrenchPublished

In Unity, an Action is a ready-made delegate that can have one or more parameters, and returns void.

They can be used to trigger game events that other scripts subscribe to, which is useful for creating connections that are loosely coupled.

Common uses of Actions include:

  • Global game events
  • Player specific events
  • Input events
  • System callbacks

The benefit of using an Action over a delegate is that you don’t need to set up the delegate template separately before creating the delegate variable.

Like delegates, Actions can be called as events using the event keyword, meaning that other classes will not be able to invoke the action, they will only be able to subscribe or unsubscribe their functions to it.

Actions can be triggered in the same way as delegates, however it’s important to check if the Action is null before invoking it, either with a null if condition or a null conditional operator.

Actions are a feature of the C Sharp programming language and, as such, require the System namespace in order to use them.

System Actions, such as these, are are are not to be confused with Input Actions, which are a feature of the Unity Input System.

public static event System.Action<string> OnGameOver;

public void TakeDamage(float damage)
{
    health -= damage;
    if(health < 0)
    {
        OnGameOver?.Invoke("The game is over");
    }
}

See also: