Events
Events are a special type of delegate function. While delegate functions can be called from any other class, events are only called by the class implementing the event. As such it's only the event implementing class broadcasting the event.
The event is implemented with the keyword event in front of the delegate type.
Other classes subscribe to an event by using the += operator (and unsubscribe with the -= operator). If the assignment operator = is used, all previously subscribed classes will be unsubscribed!
Example
This class implements an event called deathEvent.
public class Player {
// define a delegate type
public delegate void DeathDelegate();
// implement an event from that type
public event DeathDelegate deathEvent;
void Die() {
// needs a check for null!
deathEvent?.Invoke();
/*
// Equivalent to
if (deathEvent != null) {
deathEvent();
}
*/
}
}
Here is an example of a class subscribing to that event:
public class Archivement {
void Start() {
// Don't forget to use the += operator!
FindObjectOfType<Player>().deathEvent += OnPlayerDeath;
}
public void OnPlayerDeath() {
Debug.Log("Here we do the action we want to do on death!");
// As death is usually a final event of a class,
// we unsubscribe with the -= operator
FindObjecOfType<Player>().deathEvent -= OnPlayerDeath;
}
}
Actions and Funcs
Actions and funcs are simply convinient shortcuts for creating delegates. You don't need to define a seperate delegate type, as these commands create and implement them in one step.
You can think of actions and funcs as placeholders for actual functions. They can host any function that corresponds to its definition.
They are both part of the System namespace, so you need the using System; directive to make them work.
In the top example this would mean that the lines
public delegate void DeathDelegate();
public event DeathDelegate deathEvent;
can be replaced with this one line
public Action deathEvent;
These versions are available:
Actionrefers to a delegate with void return type and no parameters.Action<T>Action<T1, T2>and so on refer to a delegate with void return type and custom parameters.Func<T>refers to a delegate with a custom return type and no parameters.Func<T1, TReturn>,Func<T1, T2, TReturn>and so on refer to a delegate with a custom return type and (a) custom parameter(s). The last specified type will be the returned type.
For example
Func<int, string, bool> myDelegate;
is equivalent to:
delegate bool MyDelegate(int a, string b);
MyDelegate myDelegate;