RobinDeveloper
RobinDeveloper

Reputation: 100

What does transform do in Unity3D? behind the scenes

Due to Rider I started thinking about what transform actually does with in a class. When you call for instance transform.position does it GetComponent the transform of the object or does it have a reference to it up front? I would guess it does not GetComponent it constantly because of the efficiency of the classes but how does it actually know stuff like this. Is it all stored withing MonoBehaviour?

Upvotes: 1

Views: 880

Answers (2)

This is a good question, and not really clear from any of the documentation directly provided.

According to the same question answered over here: this.transform and this.gameObject are both cached in the Component class, which makes them faster than the generic GetComponent<>() counterpart. This has usually led me to ignore the advice that one should never use GetComponent() when one is able to cache the variable, for the transform, tag, and gameObject properties.

And as an additional treat, the Transform class implements IEnumerable that basically forces it to act as a fixed size array. Running a for-each loop on the this.transform property will give you a pass over every single child transform stored under the transform of the current object as well.

If you want to dig a bit yourself, the definitions are stored in the Component class which both MonoBehaviour and GameObject inherits from. They are hidden away in the unityengine.coremodule.dll. The UnityEngine namespace is, unfortunately, not included in Unity's git-adventure.

Upvotes: 1

Levi J
Levi J

Reputation: 95

I know this question has already been answered, but it's good to keep in mind that you don't need to worry about multiple GetComponent<>() calls anymore, as unity does background-caching, so it won't be bad for performance.

Upvotes: 1

Related Questions