✅ 1. What Is a Delegate?
A delegate is like a pointer to a function — it stores a reference to one or more methods that match a specific signature.
🎯 Delegate Syntax:
public delegate void MyDelegate();
That means:
“Any method I use with MyDelegate must return void and take no parameters.”
✅ 2. Basic Example Without Unity
using System;
public class DelegateExample
{
public delegate void GreetDelegate();
public static void SayHello()
{
Console.WriteLine("Hello!");
}
public static void SayBye()
{
Console.WriteLine("Goodbye!");
}
public static void Main()
{
GreetDelegate greet = SayHello; // Point to SayHello
greet(); // Output: Hello!
greet = SayBye; // Now point to SayBye
greet(); // Output: Goodbye!
}
}
✅ The delegate holds the method reference and you can call it like a function.
✅ 3. Delegate with Parameters
public delegate void DamageDelegate(int amount);
public class CombatSystem
{
public static void DealDamage(int dmg)
{
Console.WriteLine("Dealt " + dmg + " damage.");
}
public static void Main()
{
DamageDelegate myDamage = DealDamage;
myDamage(25); // Output: Dealt 25 damage.
}
}
✅ 4. Unity-Specific Example
Let’s say we want a Health system to notify others when the player dies.
🔹 Step 1: Declare delegate and event
public class Health : MonoBehaviour
{
public delegate void OnDeathDelegate();
public event OnDeathDelegate OnDeath;
public float health = 100f;
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0)
{
OnDeath?.Invoke(); // Notify subscribers
}
}
}
🔹 Step 2: Another script listens to the death event
public class DeathResponder : MonoBehaviour
{
private Health health;
void Start()
{
health = GetComponent<Health>();
health.OnDeath += ShowDeathMessage;
}
void ShowDeathMessage()
{
Debug.Log("The player or enemy died.");
}
void OnDestroy()
{
// Always unsubscribe to prevent memory leaks
health.OnDeath -= ShowDeathMessage;
}
}
✅ 5. Multicast Delegates
You can chain multiple methods:
health.OnDeath += ShowDeathMessage;
health.OnDeath += PlayDeathSound;
health.OnDeath += AddScore;
All 3 methods will be called when OnDeath?.Invoke() is triggered.
✅ Summary Table
Concept
Description
delegate
Defines a method signature
event
A special delegate that allows external classes to subscribe
+= MethodName
Subscribes to an event
-= MethodName
Unsubscribes from an event
?.Invoke()
Calls all subscribed methods safely
Would you like to try a delegate with return values, or use Action / Func instead of declaring your own delegate? Those are shortcuts often used in Unity too.