Cache GameObject and component references to avoid expensive lookups

Optimization principal 2: Minimize actions requiring Unity to perform "reflection" over objects and searching of all current scene objects.

Reflection is when, at run time, Unity has to analyze objects to see whether they contain a method corresponding to a "message" that the object has received - an example would be SendMessage(). An example of making Unity perform a search over all active objects in a scene would be the simple and useful, but slow, FindObjectsByTag(). Another action that slows Unity down is each time we make it look up an object's component using GetComponent().

In the olden days for many components, Unity offered quick component property getters such as .audio ...

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.