Unity Action: delegated events

Hal Brooks
2 min readMar 1, 2022

When building modular code, an action is a powerful tool to avoid having to hard code references to other game objects. An action is a streamlined version of delegate and event, so understanding these helps understand action syntax.

Cube Teleport is listening for event on Main Camera.

A delegate is a variable for functions that requires common parameters, sometimes referred to as its signature. In the Main script example below, the signature for OnSpace is a Vector3 pos. Next a public static event of the OnSpace type is declared, onPress. In void Update() if the player presses the space key onPress is used like a method if it is not null, passing the Vector3.

Delegate and event in Main script on Main Camera.

The assignment of onPress can be done on other objects, such as the Cube example below. In void OnEnable(), the Teleport method, with the required signature is added using += to the event, onPress. The Cube is now “listening” for the onPress event and will Teleport to the provided Vector3 pos when the space key is pressed. Best practice is to remove the Teleport method from the event if the object is disabled.

Setting up the Cube to listen to onPress delegate.

An action is a delegated event, as shown below, but streamlines the code to one line. Action defines the signature within the <Vector3> and assigns onPress as the event. This is functionally identical to the Main script shown earlier.

Action in Main script on Main Camera.

The beauty of an action is that they can have multiple methods assigned to them, i.e. multicast, from different objects without getting a reference to the object. The action shouts out to all the scripts which are listening.

--

--