C# delegates in Unity

Programming is one of those skills that is easy to learn but difficult to master. And it’s in that mastery that we learn to create more complex and cleaner code that will not only benefit ourselves or other as programmers but the program being developed as well.

Some programming languages, such as C# and D, provide us with delegates; a way to create functions that can be passed as parameters in other functions and executed whenever the code demands to.

While Unity does have SendMessage(string methodName) that requests the execution of a certain method in an object, that approach is not type-safe and requires reflection over the code to find such function (a somewhat costly operation). Instead, we can use delegates as the perfect alternative. I’ll be using C# but be aware that both UnityScript and Boo support it in their own way (check Unity’s Events Tutorial for an example on the last two).

In order to harness the power of delegates, we must follow this template:

Here’s a concrete example:

And if that’s not great enough, we can go even further and associate more than one function to the same delegate. In other words, whenever that delegate is called, all the functions assigned to it will be called as well. This is called Multicasting and it goes like this:

Notice that we can have two functions that comply with the same delegate, even if they have different purposes; they just need to respect the type signature of the delegate.

Also, if there’s the need to remove a certain function as a callback for a certain delegate, it’s suffice to do:

And here’s something awesome: if the function to be removed wasn’t previously linked to the delegate then it’ll simply ignore the command; there’s no need to handle exceptions or anything like it.

There are plenty of ways to obtain the same outcome using different method. Using delegates will ultimately depend on you programming style and what paradigms you prefer to use.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.