gameObject tree traversal

if I have a nested set of game objects, and I have a reference to one of the child objects (say, n levels down the tree) how do I traverse straight up, eventually finding the root?

that’s actually what I want to do, find the topmost gameObject of a tree, but I dont see anything like getTop() (to go straight there) or even getParent() (to iterate upwards

thanks to all

This stuff is contained in the Transform component. You’re looking for things like transform.parent and transform.root.

Cheers,
-Jon

perfect! thanks

I’m trying to accomplish this myself, and am running into problems obtaining a reference to parent GameObjects. In a gameobject’s Awake() code, I have this:

        GameObject go = gameObject;
        int i = 0; // safety
        while (go.transform  i++ < 5)
        {
           Debug.Log(go.transform.parent.gameObject);
            go = go.transform.parent.gameObject;
        }

The return is a null reference exception before it even prints out the log entry.

Any ideas how I can get the parent GameObject for a given gameObject?

Thanks.

Just use transform.root.