- Home /
Find the 'root' parent from children
Basicaly wand to find the main parent in a prefab like this:
Root
-child1
--grandchild1
---greatgrandchild1 <- go from here to the root no matter how deep this child is
Answer by Bunny83 · Nov 24, 2019 at 02:08 PM
As you probably know gameobjects are not in a hierarchical structure. Only the Transform components are. They build the actual hierarchical tree you see in the project view / hierarchy view. Each Transform has a parent reference to the Tranform of the parent object. So you could simply go up this chain until you reach a Transform without a parent (parent == null).
However Unity already has a convenient property that does this for you. It's called root. So when you have a reference to a gameobject or any component on a nested child object you can simply do
child.transform.root
to get the top most object that doesn't have any parent.
Answer by handerhedeghog · Nov 24, 2019 at 07:02 PM
Just use greatgrandchild1.transform.parent.gameObject to get parent object. And then repeat this procces: greatgrandchild1.transform.parent.gameObject.transform.parent.gameObject.transfrom.parent.gameObject and you will get main "root" gameobject.
Answer by ArazIbrahim · Mar 07 at 05:37 PM
private Player _player;
public void Start()
{
_player = transform.parent.GetComponent<Player>();
}
Your answer
Follow this Question
Related Questions
Zombie won't die 2 Answers
Saving Hierarchy to file 1 Answer
Health DMG 5x gameobject 0 Answers
How to reduce health on a children GameObject with my script? 2 Answers