- Home /
Accessing the Transform of a child GameObject of my Parent GameObject?
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!
Answer by CiberX15 · Apr 22, 2020 at 02:40 AM
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[i].gameObject != gameObject)
{
//This is a child transform
}
}
Okay wow, thank you a lot!
Also, so is GetComponent().GetChild(0).transform pretty much the best way if I know at what index my component is? And what would I do if I didn't know the index, the script you just wrote would be the best?
Yep. If you know the index GetChild(index) should be the fastest way to get there. And as far as I know the for loop is the fastest way if you can't guarantee the order.
If you find yourself having to run the for loop on every frame or on a bunch of objects at the same time and start seeing performance issues, you could run it once and store the result in a variable that way you only have to look it up once. Something like:
//At the top of your script
private GameObject Child = null;
//in the function where you need the child
if(Child == null)
{
Transform[] transforms = gameObject.GetComponentsInChildren<Transform>();
for (int i = 0; i < transforms.Length; i++)
{
if(transforms[i].gameObject != gameObject)
{
Child = transforms[i].gameObject;
break; //break here since we only need one so skip the rest of the loop
}
}
}
That has the advantage to that if you later destroy the child and add a new one, the code will automatically detect that Child is null again and grab the new one.
Your answer
