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!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Richard Morgan

Richard Morgan

Unity and Flutter developer interested in creating mixed-reality applications.