Delegates and Events
A Delegate is a Variable which references a Method.
The most common type of delegate is System.Action which represents a method with no parameters and void as its return type. There are also generic System.Action<T> and System.Func<TResult> delegates which can take parameters and return values. Though if you need parameters you will often want to define your own delegate type so that you can properly name the parameters, for example:
public delegate int PerformCalculation(int x, int y);
Delegates can be used as a type of Variable just like any other, except that you assign methods to them and can call them like methods (calling a delegate is referred to as "invoking" it):
using System;// For System.Action.
using UnityEngine;// For UnityEngine.MonoBehaviour.
public class Health : MonoBehaviour
{
public event Action onDeath;
private int _CurrentHealth;
public int CurrentHealth
{
get => _CurrentHealth;
set
{
if (value < 0)
value = 0;
_CurrentHealth = value;
if (value <= 0)
{
// If an onDeath delegate has been registered, invoke it.
if (onDeath != null)
onDeath();
else// Otherwise just destroy the GameObject this script is attached to.
Destroy(gameObject);
}
}
}
}
public class Character : MonoBehaviour
{
[SerializeField]
private Health _Health;
private void Awake()
{
// Register our Die method for the Health component to call.
_Health.onDeath += Die;
}
private void Die()
{
// Play a death animation.
// Turn the model into a ragdoll.
// Create an explosion.
// etc.
}
}