In C#, delegates are the containers for functions that behave like reference pointers to a method that can be used as a variable in your program. You can use C# delegates to make your code efficient and modular specially when you have a rapidly growing code base.
You can assign value to delegates and can change them at runtime. Even if you're a beginner programmer, I'm pretty sure that you know about the subscription-based services where you can subscribe to a channel, or an author. When you subscribe, you will receive the automatically receive updates from them. Delegate works exactly in that way, where the passed method gets called when subscribed and vice versa.
Practical Use case of C# Delegates
As we know objects can easily be sent as parameters in the method. But sometimes we might feel the need to be sent a method as a parameter of another method that's when we will need the delegates.
Type of Delegates
There are two types of delegates.
- Single Delegate – A single delegate can reference only one method at a time.
- Multicast Delegates – A multicast delegate can store references of multiple methods at a time.
Examples of using C# Delegates in Unity
Here are some of the examples that will help you understand the concept better.
Declare a Delegate
Subscribe to Delegates
Unsubscribing from a Delegate
Now, let's put everything together and see in action. Let's create the new class named
DelegateTester and attach the script to an empty game object.
Now create a new cube and attach the new script named
ObjectController. And add the below code to that script.
When you run the game you will see it will call the assigned method. It concludes that any class can subscribe
ONChangeProperty delegates and get a callback when this gets called.
Thank you for reading till the end. You can leave comments if you have any queries or feedback.