Hello,
When I wanted to access the transform of a child (a gameobject) of a parent (a gameobject) that was my first intuition : gameObject.GetComponent().GetComponentInChildren().transform;
But actually, the solution I found after messing around was GetComponent().GetChild(0).transform;
I understand why this solution is working, but I don’t understand why my first idea is not working, and I think I would understand a lot if i understand this part.
For example, I don’t understand either why gameObject.GetComponentInChildren().transform; would also not work. When I do this, it get’s the parent transform and not the child transform and I’m really confuse why.
My parent Gameobject have only one child with one transform.
Thank you!
So GetComponentInChildren() is actually slightly misleading. It actually returns the matching component in the transform hierarchy INCLUDING the game object it was called on. So since all game objects have a transform, it will always return the transform of the object you called it on.
This means GetComponentInChildren() is only useful when you are dealing with a component that doesn’t exist on the root object.
If, like with transforms, the component you are looking for exists on the parent and the child you can use GetComponentsInChildren() (note the s) like this to ensure you are getting the child component:
Transform[] transforms = gameObject.GetComponentsInChildren<Transform>();
for (int i = 0; i < transforms.Length; i++)
{
if(transforms*.gameObject != gameObject)*
{
//This is a child transform
}
}