Unity — Using Delegates and Events
Here’s a very simple example that demonstrates the power of delegates and events. Clicking the button turns the cubes red:
All the cubes share a script that contains the function for changing the color to red:
But they also use a method to assign the TurnRed() function to an Event called onClick that’s found on another script called Main:
In the Main script (attached to the MainCamera), onClick is defined as an Event that is attached to a delegate called ActionClick():
So the TurnRed() method is attached to the onClick event that’s been added to the ActionClick() delegate. To trigger the onClick event, let’s add a function to Main called ButtonClick():
Create a new button and add the MainCamera (since we’ve added the Main script to it) then set the MainCamera to the On Click function of the button and assign the ButtonClick function:
Now wen the button is clicked, it will call the ButtonClick function, which will trigger the onClick() event, which will execute all the TurnRed methods within the ActionClick delegate.
Here’s the complete code:
This might see a bit confusing at first, but all that’s happening here is that we are stacking functions onto a delegate that’s triggered by an event. Simple and powerful!