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 ...

Get Unity 5.x Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.