Delegate Pt.1- C# Skill in Unity: 10

S.J. Jason Liu
4 min readOct 4, 2021

--

Objective: an introduction of Delegate in Unity.

Delegate is a function that makes methods become variables and easy to access across scripts. It would make scripts from different objects can access the delegate function with assigned parameter.
In other words, delegate allows scripts can easily access the method without getting the reference.
In this tutorial, I would make a quick introduce of delegate and the extended way of using a delegate.

Delegate

To declare a delegate, we would declare a method as declare a variable.

We have declared a method with “void”, method name, and no parameter.

Next we would need to create a method to assign this delegate method.
Then create another method to show some message.

Now we can assign “message” to “ShowMessage()” in Start().

Make a null check to prevent some unexpected error.

Add this script to main camera and you should see the message when Play test.

Delegate with multi methods

Delegate can also process multiple methods within, by using “+=” to assign to methods.

Duplicate ShowMessage() with multiple methods and number them to identify.

Then add these methods to “message” by using “+=”.

Test it again and it should print out all results.

Delegate with events

The core rule of using a delegate method, is to make sure the type of method and type of parameter are all same. With this rule, we can use events to make delegate method can be accessed by other scripts.

Let’s make the health decrease 1 every time when we pressed space key, and reveal the result on UI.
To do these, we will have an UI canvas with text, and a UIManager script to do the calculation to show on text.

Let’s create a delegate method with integer parameter. To get a better use of delegate without setting reference, set the delegate to static, and set is as event.

Then we need to create an integer variable as default health. And create a space key detection in Update() to decrease health.

Now we can call the delegate method, and do not forget doing the null check.

After setting function that pressed space key, now we can call this delegate method in UIManager.
All we have to do is adding the method of updating text to delegate method in OnEnable().

Now we can Play test it and press space key to check the result.

That is all of this tutorial. In the next tutorial, we would dig more extra usage of delegate.

--

--

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.