Component caching, good or bad

in a script with several component lookups, i believe this is a quick optimization fix, does anybody see any drawbacks with this?

in c#:

new Transform transform;
new Rigidbody rigidbody;

void Awake () {
    transform = gameObject.transform;
    rigidbody = gameObject.rigidbody;
}

That’s what the docs recommend. I’d suggest using variable names other than “transform” and “rigidbody”, since normally those alone refer to the transform and rigidbody of the gameobject. The drawback would be increased memory usage (not much though).

–Eric

the point of my post was specifically the use of the same name, as a convenient way of optimizing an already large script without changing the script

i believe the new keyword will still create space in memory for the member, as the shadowed member will still hang around, just ‘shadowed’

The only problem that could arise as far as I can see is if the class actually requires the uncached components, which should only really happen if components are added/removed mid scene.

Other than that, it’s a fairly sound and safe optimization.

Interesting. I’ve gotten in the habit of using

Transform tranzform = transform;

but if I could use better spelling, I would prefer it! So if you do this…

Transform transform = transform;

…you will refer to your local variable, and not be using the GetComponent() shortcut?

Yup, effectively shadowing the base transform (and its call to GetComponent).

C# complains about the shadowing and requires you to use the ‘new’ keyword. I don’t know about javascript, but I guess its the same.

Rock on. We help each other this morning! :smile:

Is there any way to use this technique to be able to use the same name for a public and static variable? I love to assign variables in the inspector, but be able to use them in other scripts without having to create references. When you use the static keyword, the variables are no longer editable in the inspector, but I’d rather not have to “rename the variables” in order to use them elsewhere. (This is also a waste of memory.)

that would be pretty handy, unfortunately couldn’t find any semantics that would allow me to do this and preserve Unity reflexion.