- Home /
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 gameobject:
-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.
I'd take a step back and consider your architecture; you have thousands of levels of children? Don't know what kind of game you're making, but that just doesn't sound right. Why do you need that many individual gameobject entities in the scene? And why exactly are you trying to find an arbitrary one of them? I couldn't quite follow your description of your UI panel. A screenshot might help.
No, there is only 3 or 4 levels of children but total number of child objects are almost 1000. In scene, there is a room modeling and there is a list of all these objects (buttons) like a "hierarchy tree view" in my UI panel. When I will click on any button (they are created at runtime), color of this object ,which clicked button refers, should be green for example. Therefore, I should get a reference of these objects and I am trying to find the way which is the best and fastest. I hope I was clear.
In scene list of buttons look like that too;
-Object1
-----Object2
---------Object3
---------Object4
-----Object5
---------Object6
---------Object7
-------------Object8
-----Object9 ...