gameObject.transform performance questions

Ok I read a lot about things like this:

Transform thisTransform;
GameObject otherObject;
Transform otherTransform;

Start()
{
thisTransform =  this.transform;
otherObject = GameObject.FindWithTag(...);
otherTransform = otherObject.transform;
}

My question is: does it make a difference whether I use otherObejct.transform or otherTransform every update? Does it even make sense to store thisTransform or is this just a myth flying around for years without any reason?

Using otherTransform is faster than using otherObject.transform.

Whether or not it makes a real world difference in your specific game, you should figure out by profiling your game and see where your bottleneck is.

otherObject is just a reference for the GameObject. So every time you call otherObject.transform, you have the engine running a search function for the transform component on the otherObject. Search functions are costly, so doing them all in your start or awake function is less expensive.

So yes, otherTransform is going to save you time and resources.

Great, thanks for the fast response. I will go with otherTransform wherever possible then.

The desktop version of my game runs with 40 FPS on iOS devices, but I will take the time to optimize the whole thing as much as possible.

C# provides you with the ability to use transform, and not have it do a GetComponent behind the scenes:

new Transform transform;

Then set it up like you did. I prefer Reset() to Start().

I’m using C# for such a long time an I actually never used that before, but it sounds just great!

So you basically say I should do this:

new Transform transform;
void Start()
{
  transform = gameObject.transform;
}

If I have a MonoBehaviour called “Actor” and a second one “Enemy : Actor” and I put the code above into the “Actor” class, do I have to put it in “Enemy” too, although it already gets the whole stuff from the Actor class? If yes, do I have to put both the new and the Start() into the “Enemy” class?

EDIT: after some trial and error it seems like I have to do it in every subclass.
EDIT2: ok after some additional trial and error it seems like it DOES work in the subclasses without pasting the code in every single one of them. That would be pretty great :slight_smile:

protected new Transform transform;
protected void Start()
{
   transform = gameObject.transform;
}

Don’t forget the protected, if you use Start() in the subclasses you have to call base.Start()

2 Likes