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

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.

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.

private Player _player;

public void Start()
{
    _player = transform.parent.GetComponent<Player>();
}