Get Top Level Parents?

I am working with a child of a game object, and I need to get the child’s parent. Here are pictures to show you what I mean:

Parent game object:

Child game object:

So basically, I need to get the “Player” game object, without using transform.parent.parent.parent or GameObject.Find()

You could put a script on the root of the entire object that contains references to everything anyone using that object would need to find.

For starters:

 public Transform HoldPoint;
 public Transform Player;

Drag those references in there when the prefab is created (or when those objects are created in code) and then anyone who has a reference to that root script can get at the parts they need.

1 Like

I already have a PlayerManager. But it’s fine, I solved it another way lol. Thanks anyway though.

Tried transform.root? It does the job exactly.

Often this structure breaks down in the long run, I personally use a recursive search to check each parent until the root is found or the component of interest is found. That way you are not constrained to having everything as root.

2 Likes

I tried transform.root, but it gave me the VEEERY top parent, which is not at all what I wanted lol.

Did you try the recursive search? It looks something like this. (Be warned its easy to make a infinite loop accidentally, proceed with caution.)

public static T GetComponentInParents <T>(GameObject startObject) where T : Component
{
    T returnObject = null;
    GameObject currentObject = startobject;
    while(!returnObject)
    {
        if (currentObject == currentObject.root) return null;
        currentObject = curentObject.transform.parent;
        returnObject = currentObject.GetComponent<T>();
    }
    return returnObject;
}

You can also mess with this so that it will check itself, instead of starting with the first parent.

And its totally untested, so it might not compile. But you get the idea.

Edit: Unity has this function built in already. I swear that is new and wasn’t there last time I tried to solve this problem.

http://docs.unity3d.com/ScriptReference/Component.GetComponentInParent.html

6 Likes

Thank you man, you are a really helpful person around these forums ha ha.

1 Like
Transform topParentTransform = transform.root.transform;
2 Likes

Thank you. i learned from you.

You guys mean “transform.root”