- Home /
Question by
michaelb212 · Aug 05, 2015 at 12:46 PM ·
transformoptimization
Why should i save transform as member ?
I am going through some scripts I got from the asset store and I noticed that before a script uses the transform it store it as a member first in the awake call
private Transform m_Transform = null;
void Awake()
{
m_Transform = transform;
}
void Update()
{
... do something with m_Transform ...
}
Can anyone think of an explanation for why is that good for ?
Comment
Best Answer
Answer by bkevelham · Aug 05, 2015 at 12:48 PM
transform
is a property. Whenever you call it, behind the scenes it gets the Transform component which is attached to the GameObject, which is a fairly expensive operation.
So if you use transform
a whole lot, particularly within Update()
you're sacrificing performance where you really don't need to. That's why you'd cache it.