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
to reference the AudioSource
component of a script's parent GameObject, rigidbody
to reference the RigidBody component, and so on. However, this wasn't a consistent rule, and in other cases, you had to use GetComponent...