To cache or not to cache a reference?

In a previous tutorial, in order to disable the gravity, we first cached a reference to a rigidbody (i.e. created a Rigidbody type variable) and then used .useGravity on this variable. Here is how it kind of looked:

Rigidbody rigidBody;
rigidBody = GetComponent();
rigidBody.useGravity = false;

However in this tutorial, in order to disable the movement script, we use the GetComponent() and use .enabled directly on this. And here is how this one kind of looks:

GetComponent.enabled = false;

Both options work but I would like to know the difference between these two options. Thank you.

When you use GetComponent<Rigidbody>() you are calling a function that takes some time to complete. If you have Rigidbody rb = GetComponent<Rigidbody>() you have still used some time to get a reference, but after that just using rb.useGravity = false is faster, code wise.

So you do the GetComponent<>() stuff once in the Start() section, but only use the cached rb in the Update() section

This won’t make much difference in the relatively simple projects for the lectures, but in a larger game with 100’s of components it would be significant. You don’t want to call unneccessary functions every frame, only do the minimum required to update the scene in Update().

1 Like

Thanks a lot for the feedback.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms