Home > Software design >  Why don't you need to use GetComponent on Transform?
Why don't you need to use GetComponent on Transform?

Time:06-24

So I've noticed that in order to use properties of SpriteRenderer, you need to get the component first but the same isn't done for Transform.position. Isn't Transform another component like SpriteRenderer?

CodePudding user response:

Yes, Transform is just another component of the system. The same is about RectTransform, which is used in the unity UI system (canvas).

Several years ago as far as I know, transform property was just syntactic sugar over GetComponent<Transform>() code, as any GameObject has this property and it is accessed quite often. Also, because of the underlying GetComponent call, which is not completely free there was a recommendation for a long time to cache this property if you need to access it often (assign it to a class member and use this member instead of this.transform).

Right now, as far as I know, caching has no sense in most cases, as all components are stored in the array internally, and Transform always has an index 0, so accessing transform is just an access to the first element of the array. Anyway, if someone has really tons of calls to it, it can be useful to profile this, but I don't think it will be an issue in most cases.

But some dinosaurs like me still cache it out of habit :D

CodePudding user response:

In low level side, most all components (or objects) inherited from Transform, which is a basic element in game Engine. Then you'll realize most objects created from layout would have Transform component at least.

  • Related