Assigning to global transforms of current gameobject

For optimization, is it necessary to assign to global the transforms of the gameobject the current script is in?

i.e., start(){var t:transform;} update(t.position+=Vector3(x,y,z))

Actually, your code won’t work :wink:

function Start () {
     var t = transform;
     //local variable declaration.  Only accessible from within this function
     //goes out of scope when the function returns.
}

function Update () {
      t.position += Vector3();
      //What's "t"
}

Sorry to point that out, but its an important mistake, Caching the transform to a local variable will not do you any good.

  1. It will go out of scope at the end of the function. That means that it can’t be accessed any more and it will be marked for garbage collection. So now you’re back where you started. :slight_smile:
  2. You’re just allocating extra memory. Creating a reference type like that puts memory on the heap.
  3. No other functions can use it. Like #1, you will cache the variable, just not in a useful place. Given it is a local variable, it isn’t accessible from outside the function.

But, caching component look ups is a good optimization to perform. It saves Unity from having to find the component attached to the game object every time that you access it. This page explains it fairly well.

var t : Transform;
function Start() {
    t = transform;
    //cache a reference to the Transform so that Unity doesn't need to find it again
}
function Update() {
    t.position += Vector3();
}