Roger Wang
Roger Wang

Reputation: 595

Why does Unity use transform instead of gameObject with some functions such as GetChild()?

Unity uses transform.GetChild(childNum) as opposed to gameObject.GetChild(childNum).

I understand that every GameObject in Unity has a Transform component and the function returns the Transform of the child, but wouldn't it be more logical to use the GameObject class to get a child as it refers to the actual GameObject in the scene or project and not just a component? Why is the Transform used for finding hierarchical information?

Upvotes: 5

Views: 1457

Answers (2)

Confused
Confused

Reputation: 6278

Why is the Transform used for finding hierarchical information?

Because the transforms serve as (and are) the anchors between children and parent, both figuratively and literally.

Upvotes: 5

Blindleistung
Blindleistung

Reputation: 702

It appears a little strange, but that is just the way it is. The transforms maintain the position and size, and the transformations are merged in sequence to get the final location, rotation, skew and scale of an item. So it appears that they are what keep the connection for efficient traversal of the engine for rendering and for updating rotation and position in the children.

Thus that is just the way it is defined in Unity. To get from a gameObject to the first child, you need to go (this).transform.getChild(0).gameObject .

OBJ_A        -->   transform
                       |
                       V
gameObject   <--   transform.getChild()

Is just a matter of definition. Will not change in the future (unless looking at DOTS).

Upvotes: 1

Related Questions