Caching the ‘transform’ and ‘gameObject’ properties

The transform and gameObject properties of MonoBehaviour are often used to check property values against other values.

There are a few reasons to avoid using transform to move objects, but a position-check is a perfectly valid example. There is, however, a small problem with the above code: The transform property internally does a GetComponent() call. This means, that every frame a method call is needed to find the reference to the Transform component of our GameObject.

This code illustrates what is actually going on under the hood of Unity. At this point it is not necessary to fully understand how these internal calls work, just keep in mind that every method call and dot-operation costs performance and therefore we want to avoid them as much as possible.

The solution: Cache your variables and even Unity properties!

Instead of finding a reference to our Transform component in every frame, we do it only once and store it in a variable. You could call this variable myTransform or something, but I prefer to call it the same as the Unity transform property. This way, I don’t have to change any of my working code, when I want to optimize things at the end.

Pay attention to the new keyword, which we use to tell the compiler that we intend to override the inherited member transform from MonoBehaviour. This step is not entirely necessary, but sometimes Unity will throw a warning and remind you that there already exists a variable called transform.

Caching references in variables is a common way to optimize performance.

What we did with the transform property is just one example of caching a reference for later use. We do the same thing whenever we access another script or component, but in case of the built-in Unity properties, I think it is worth mentioning that we can override those with more performant ones.

Note, that this kind of optimization is only effective and noticeable when resources are limited or you are dealing with many script objects. Caching Unity properties for only your player will not speed up your game visibly!

Published by

Chris Yarbrough

Game Design student at Mediadesign Hochschule, Munich.

Leave a Reply