Delegates

Gerald Clark
3 min readJan 2, 2023

What the heck are delegates? Delegates can be thought of as a variable that holds a method or several methods.

To declare a delegate:

  1. Use the keyword delegate.
  2. Give it a method signature. The method signature is going to be of the type of method you want to hold.

And thats it. In my example I’ll cover how to change the color of an object’s material using a delegate.

First I declared my delegate. I assigned it a void type since I dont want to return anything and then gave it a parameter Color and named it newColor.

All I’ve done here is defined the signature for the delegate.

The next thing to do is create a variable of type ChangeColor and name it.

SO now I have the delegate decalared and a variable declared that uses the ChangeColor type.

I can use this by creating a method called UpdateColor() and feeding it the same parameters as the delegate.

As you can see here, I’ve assigned the colorChange variable to the method, UpdateColor().

How can we invoke these?

What I can do is take the colorChange variable and give it parameters. For this example I’ll use Color.green.

So now when I add this script to the Main Camera for example, run the application, and check the console, you’ll see the color change Debug.Log message appear.

One cool thing about delegates is that they are multi-cast. This means you can stack several methods into 1 delegate. For example:

I have 3 methods I want to assign to my taskComplete delegate. To do this, I simply assign the methods to the tasComplete delegate with the += operator.

Running this will print the debug.log messages in each method when you call the method in start:

You can also remove the methods with the -= operator.

I’ll get more into that in the next article where I’ll cover Events!

Hopefully you can see how this could come in handy!

--

--

Gerald Clark

Father Game Developer Music Composer Sound Designer