,I know how usually if you reference another object or component more than once then it’s good practice to cache them as variables to increase performance. However, I’ve only ever done this on a global scale (at the top of the script). I’m wondering if caching the references within a method would have the same effect or if the variable’s value would be updated every time the method is called thus being pretty much useless for performance.
Here’s an example:
using UnityEngine;
public class Stuff : MonoBehaviour
{
// Option 1
Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
// Later on do stuff using rb
}
// Option 2
void Update()
{
Stuff();
}
void Stuff()
{
Rigidbody rb = GetComponent<Rigidbody>();
// Do stuff using rb
{
}
Of course it will and you should do it when appropriate. Common examples are components which you can not cache in the class itself because the depend on external information. For example inside OnCollisionEnter you may want to access a component on the other object you collided with. So you can not save a reference in the class and you have to use GetComponent. However you only ever want to use GetComponent once per component inside the method.
Note that the improvements are in the micro optimisation scale as GetComponent isn’t as bad as it’s often stated. It litterally just searches through the internal list of components on a gameobject on the native side. Usually you only have a hand full of components on a single gameobject. So looking up a particular component is just a matter of doing a few loop iterations and checking the type.
Though it’s actually more a matter of style. This applies to all sorts of other cases. Like accessing fields of a class that is stored in an array. Instead of doing
for (int i = 0; i < someArray.Length; i++)
{
someArray*.fieldOne = 5;*
someArray*.someOtherField = 6;*
someArray*.ABCD = 42;*
}
it’s generally more readable and slightly better for performance to do:
for (int i = 0; i < someArray.Length; i++)
{
var obj = someArray*;*
obj.fieldOne = 5;
obj.someOtherField = 6;
obj.ABCD = 42;
}
This of course has an even greater effect of the access of the instance is more complex. It also gives you a chance to choose a better local variable name so the intention of the code becomes more clear to the reader. I don’t quite understand why some people are obsessed with one-liners. In most cases they are hard to read, harder to debug and don’t provide any actual advantage except saving a few lines of code. Unless you apply for the [International Obfuscated C Code Contest][1], keep your code readable and debuggable. Having a one liner means if you have any kind of error in that one line makes it much harder to find the error. Splitting the code into multiple lines helps to isolate the issue.
[1]: International Obfuscated C Code Contest - Wikipedia