Codementor Events

Delegates In Unity

Published May 27, 2021
Delegates In Unity

Introduction

Delegate is a container for a function that can be used as a variable. Delegate helps in making code modular and efficient. It works like a subscription-based service, where the passed method gets called when subscribed and vice versa.
There are two types of Delegates
Single-Cast Delegate — can hold single method.
Multi-Cast Delegate — can hold multiple methods.

Getting Started

Declare Delegate

Delegates in C# can be defined by using delegate keyword followed by return-type, name, and parameter.
Member variable can be declared by using member-type followed by a variable name.
//Defining Delegate
public delegate void MyDelegate();
public static MyDelegate myDelegate;

Using Single-Cast Delegate

Declared methods can be assigned to Single-Cast Delegate using “=”.
//Subscribing to Single-Cast delegate
myDelegate = myMethod;

Using Multi-Cast Delegate

Declared methods can be assigned to Single-Cast Delegate using “+=”.
//Subscribing to Multi-Cast delegate
myDelegate += myMethodOne;
myDelegate += myMethodTwo;
De-Assign method from delegate
To De-Assign methods from delegate, “-=” is used.
//UnSubscribing to Delegate
myDelegate -= myMethod;
myDelegate -=myMethodOne
myDelegate -=myMethodTwo

Calling Delegate

Delegates are called like methods.
//Delegates without parameters
myDelegate()
//Delegates with integer as parameters
myDelegate(20)

Understanding Delegates

Delegates are used to perform tasks assigned to different methods with one call. The feasibility of subscribing and un-subscribing methods helps programmers to develop efficient and easy-to-expandable code structures.
Delegates vs Events
Events and delegates, both works on subscription-based service, but Delegates are independent of Events, whereas Events are dependent on Delegates and cannot be created without Delegates. Delegates are able to pass parameters, whereas Events are incapable of passing parameters.

Example Program

using UnityEngine;
using System.Collections;
public class DelegateHandler : MonoBehaviour
{
public delegate void MyDelegate (string m_name);
public static MyDelegate myDelegate;
public void Start()
{
myDelegate = PrintName;
myDelegate("John");
}
public void PrintName(string name)
{
print(name);
}
}

Output

John

Conclusion

Delegates are efficient, and helps to create modular, expandable, and re-usable code, but should be un-subscribed when required or may lead to memory leaks.

Discover and read more posts from Himanshu Nag
get started
post commentsBe the first to share your opinion
Show more replies