Improving efficiency with delegates and events and avoiding SendMessage!
Optimization principal 2: Minimize actions requiring Unity to perform "reflection" over objects and searching of all current scene objects.
When events can be based on visibility, distance, or collisions, we can use such events as OnTriggerExit
and OnBecomeInvisible
, as described in some of the previous recipes. When events can be based on time periods, we can use coroutines, as described in other recipes in this chapter. 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...