Delegation is a powerful concept that is used as a way to notify other classes when something happens.
You can think of delegates as reference type variables used to hold the references of methods that have the same signature as the declared delegate.
When the delegate is called, it will notify all the methods which are being referenced by that delegate.
Before we dive deeper in the concept of delegation, I want to mention that this tutorial is suited for beginners, intermediate and advanced Unity users.
However, if you are a beginner, I expect you to know your way around Unity.
I expect that you know how to create a new project, how to create a class, how to attach a class to a game object, I expect you to know the basics of programming with C# in Unity, how to print to the Unity console and other basic beginner stuff.
If you don’t know these things, then you should check out my C# tutorial series starting with variables.
After that go through my Rainy Knifes tutorial.
How Do We Declare Delegates And Events
For starters, I’ve created a new Unity project and inside I created two scripts. One is called Sender, the other is called Receiver.
Create an empty game object in the Hierarchy tab, name it however you want, and attach the Sender and Receiver scripts on it.
Make sure that you do these steps before you proceed with the tutorial.
Going back at the task at hand, how do we declare a delegate and how do we declare an event?
Inside the Sender script, write the following line:
public delegate void PlayerDied();
The keyword delegate denotes that this is a delegate. The name of this delegate is PlayerDied, you can, of course, name the delegate however you want, and the name will be meaningful e.g. it will reflect what the delegate’s purpose is, and the same naming conventions that apply for functions apply for delegates as well.
You will also notice that we have the keyword void in the delegate’s declaration. This is because the delegate can return a value, or it can be void and not return anything, we will see examples for both cases.
Next we declare an event for the delegate:
public delegate void PlayerDied();
public static event PlayerDied playerDiedInfo;
What Is The Difference Between The Delegate And The Event
Subscribing To Events
public delegate void NewspaperCompany();
public static event NewspaperCompany newspaperSubscription;
Well, we see that the delegate is declared as void, which means it doesn’t return a value, the function we wish to subscribe to the event also needs to be void.
void NewspaperReceiver()
{
}
The NewspaperReceiver has the same signature as the NewpaperCompany delegate and this is the function that we will use to subscribe to the event.
To subscribe to the event, we need to write the following line of code:
Sender.newspaperSubscription += NewspaperReceiver;
private void OnEnable()
{
Sender.newspaperSubscription += NewspaperReceiver;
}
private void OnDisable()
{
Sender.newspaperSubscription -= NewspaperReceiver;
}
Calling The Event And Informing Subscribers
Now that we subscribed to the event, let us see how can we call it.
First I am going to add a line of code in the NewspaperReceiver that will print to the console so that we know when it executes:
void NewspaperReceiver()
{
Debug.Log("Function called by the event");
}
Going back inside the Sender script, this is how we call the event:
void Start()
{
if (newspaperSubscription != null)
{
newspaperSubscription();
}
}
On line 5 you will notice that we call the event like a function, but before we do that we need to test if the event is not null.
The event will be null only when there are no functions in any class that are subscribed to it, in our case the event is not null because we subscribed the NewspaperReceiver function to it.
If you call an event that has no subscribers to it, you will see a null reference exception warning in the console, that’s why we first perform a test, like we did on line 3 to check if the event is not null.
When we call the event, it will inform all functions that are subscribed to it, and yes, you can subscribe multiple functions to the same event, no matter if there are 2, 10, or 100 functions subscribed to that event, all those functions will be called.
Now let’s run the game and see what will happen:
What Is The Purpose Of Delegates And Events And When Should I Use Them In My Game
Passing Parameters With Events
I already said that the delegates can take parameters, so let’s modify our delegate and event to take a parameter:
public delegate void NewspaperCompany(string msg);
public static event NewspaperCompany newspaperSubscription;
Now that the delegate takes a parameter, we need to modify our function that we will use to subscribe to the event so that it has the same signature as the delegate:
void NewspaperReceiver(string msgFromEvent)
{
Debug.Log(msgFromEvent);
}
The way we subscribe to the event will stay the same:
private void OnEnable()
{
Sender.newspaperSubscription += NewspaperReceiver;
}
private void OnDisable()
{
Sender.newspaperSubscription -= NewspaperReceiver;
}
When we call the event now, we will provide the required parameter that will be passed further to the function or functions that are subscribed to that event:
void Start()
{
if (newspaperSubscription != null)
{
newspaperSubscription("Printing the parameter from the delegate");
}
}
When we run the game this is what we will see:
Now we see that what we passed as a parameter from the event to the function, is printed in the console.
Of course, delegates are not limited to one parameter and type of the variable that you can use as a parameter. You can have as many parameters as you want and they can be different types of variables depending on your needs.
Returning Values With Events
public delegate int NewspaperCompany(int a, int b);
public static event NewspaperCompany newspaperSubscription;
int NewspaperReceiver(int a, int b)
{
return a + b;
}
private void OnEnable()
{
Sender.newspaperSubscription += NewspaperReceiver;
}
private void OnDisable()
{
Sender.newspaperSubscription -= NewspaperReceiver;
}
When we call the event to inform the subscribed function, we can store the returned value in a variable:
void Start()
{
if (newspaperSubscription != null)
{
int sum = newspaperSubscription(2, 3);
Debug.Log("The sum of a and b is: " + sum);
}
}
When we run the game we will see the sum of a and b printed in the console:
2 thoughts on “Delegates And Events In Unity – What Are They And How To Use Them”
Got it now, thank you
Thank you very much!