- Home /
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))
Answer by Peter G · Jun 11, 2011 at 07:30 PM
Actually, your code won't work ;)
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.
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. :)
You're just allocating extra memory. Creating a reference type like that puts memory on the heap.
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();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612103120im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Are .gameObject and .transform both using GetComponent() in the background? 1 Answer
Component without gameObject 2 Answers
How to Change Background Sprite at run time ? 0 Answers
Transform vs Gameobject 3 Answers
Calling gameobject.transform vs. just calling transform directly - Performance negligible? 1 Answer