- Home /
Access GameObjects Parents and Childs from any level of hierarchy
Hi there, I am having a hard time trying to access an object from a script. The hierarchy levels looks something like this
parent
child_0
child_2
child_1
I have a Script attached to child_1
, with a collision controller. How can I access to child_2
from the script in child_1
to enable child_2
, which is disabled by default? I have tried a few ways, but I can't figure it out. I can, for example, do something like (I didn't try it, I don't know if this works):
GameObject.Find("parent").gameobject.GetComponent<Transform>().GetChild(0).gameobject.getComponent<Transform>().GetChild(0).gameobject.setEnable(true)
But I suppose there should a way to access it from child_1
.
Your code bit seems to be unneccessarily complex, and GetComponent is pretty expensive ;)
How about just keeping a reference to the child GameObject, or child's component, in a script?
Also, you can always use transform.parent for the direct parent or transform.root for the root parent of the whole hierarchy.
Your answer
![](https://koobas.hobune.stream/wayback/20220612094520im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Parent class in getcomponent 1 Answer
GetComponent - Root Hierachy 2 Answers
How can Use Child Local Position 1 Answer
Get children of another object in hierarchy. 1 Answer
PowerUp mechanics doesn't works 0 Answers