How to get the GameObject reference with using trees in script?

Hello. I have an object which has too many children, grandchildren and children of grandchildren (both more than 1000). Example structure of hierarchy for that game object:

-Object1
-----Object2
---------Object3
---------Object4
-----Object5
---------Object6
---------Object7
-------------Object8
-----Object9 …

Also I have an UI panel and I create empty GameObject for each object in that panel at runtime. I could do that with “for” loop and set them using AddComponent and GetComponent for making them “Text”.

I know there are many ways to get GameObject reference and the most common one is GameObject.Find();

Because there are too many objects in my hierarchy and GameObject.Find(); has performance problems, I should find another ways. I tried;

 room.gameObject.transform.GetComponentsInChildren<Transform>()[n].gameObject;

and

 room.gameObject.transform.GetChild(n).gameObject;

(room object is a root of that game object which I wrote it as a public GameObject in script)

but I am not sure how they affect performance. Then, I thought that maybe I can use trees because from data structures we know that they are faster search tools. However, I couldn’t built tree in script with C#.

If you have better idea than trees, I also want to hear that. Thanks in advance.

Here is a possible tree search function

public GameObject FindByName(GameObject parent, string name)
    {
        if (parent.name == name) return parent;
        foreach (Transform child in parent.transform)
        {
            GameObject result = FindByName(child.gameObject, name);
            if (result != null) return result;
        }
        return null;
    }

But if your tree don’t follow specific rules (binary search tree for exemple), you can’t do better than unity in my opinion.

1 Like

If you want the most performant way to do this: Add a script to each object you may want to find. This script will crawl up the hierarchy via transform.parent until it finds the Manager class (which will be on the root object). The Child class adds itself to a dictionary of objects in the Master. From there, the Master will be able to access these objects effectively instantly by name, and it won’t be especially demanding at initialization either.

This tree function works perfect on my code. what do you think about its effect on performance? I ask it because when program runs I can’t understand how performance changes. Is there anyway that I can follow speed of functions during runtime? Can “Profiler” help us? Thank you very much.