GameObject vs Transform Caching

We had a discussion in the office today about caching of gameobjects and transforms and came to the (somewhat obvious) conclusion that its far better to cache transforms, since we operate on them more frequently. If we cache the GameObjects, we guessed Unity has to do an internal GetComponent to find the transform. And since we can get the GameObject from the transform, there wasn’t any major problem we could foresee.

We are rewriting a major part of our app based on this assumption, and any feedback would be appreciated.

GameObject.transform is a property, but I would assume that the getter of that property does a fast internal lookup against a table or the like to speed things up.

Still slower than referencing the transform directly like you said, but probably not a serious slowdown.

To speed things up even more, and perhaps simplify some of your code, you could write your own container that holds a reference to the Transform, plus references to any of the other Components you need to access from the GameObject. This way you store just what you need, and you always have quick access to it as long as you have a reference to your container class.

Saves doing any GetComponents, and you can add custom indexing, utility code, or whatever else you may need.

-Jeremy

I was under the impression that gameObject.transform–and rigidbody and the other basic types–are all GetComponent() calls behind the scenes.

We always do a private cache of transform or rigidbody if we act on them in updates. I still don’t get why Unity can’t optimize this for us. At Unite there was some mumbling about memory consumption as the reason, but doesn’t make any sense to me…

Thats what I thought too, and the script reference seems to say the same.

When we access a component through an accessor variable for the first time, would it not be possible to cache it for later use? Checking if the accessor is used within an Update, LateUpdate or FixedUpdate call would help avoid wasting memory.