- Home /
What's the most efficient way of finding child objects at runtime?
I have a prefab that will be added to X amount of objects, and these prefabs have Y amount of child objects. These child objects have a few objects under them too.
What I would like to is to be able to access them locally per gameobject I instantiate them at like this:
Prefabname.Childname.ChildsChildname.TheObject.setActive(true);
Is this possible? It would save me a lot of time.
Thank you very much for helping out.
Answer by jmgek · Dec 22, 2016 at 05:24 PM
While you can search through transforms in order to find their children I would suggest creating a list of children on the parent object that would store the children.
This is faster than searching the entire scene for a game object by name or tag. And in most cases the best way to refence objects.
How are you creating the children? Are you actually instanceing or are you just setting them active?
Either way on instance or start you can use:
//parent list holder. Cs
List<gameovject> children...
//child
This. Game object. Transform. Parent. Getcomponent<listholder>().children.add(this.gameobject)
Sorry on my phone, this adds to a parents list of children by using the child object to populate it. Use can use this recursively to search any amount of children as long as they have a list and that code.
Does that make sense? Is this what your looking for?
Hi, The Prefab has all the childobjects on it already. The only thing instantiated is the Prefab itself.
Using a list is what we decided to try as well, but I will get to test this tomorrow, so yes, this is something I looked for.
No worries, yes that logic will work if you put it in the class 'start or constructor' on any game object. It's basically registering itself to a parent.