Publisher-Subscriber pattern C# delegates and events
When events can be based on visibility, distance, or collisions, we can use such events as OnTriggerExit
and OnBecomeInvisible
. When events can be based on time periods, we can use coroutines. However, some events are unique to each game situation, and C# offers several methods of broadcasting user-defined event messages to scripted objects. One approach is the SendMessage(...)
method, which, when sent to a GameObject, will check every Monobehaviour scripted component and execute the named method if its parameters match. However, this involves an inefficient technique known as reflection. C# offers another event message approach known as delegates and events, which we describe and implement in this recipe.
Delegates and events work in a similar way to SendMessage(...)
, but are much more efficient since Unity maintains a defined list of which objects are listening to the broadcast events. SendMessage(...)
should be avoided if performance...