The most resource efficient way to dynamically find specific child in parent?
Hello, I have a >1000 parent GameObject and each has 5 child GameOjects with same names (title, description, author, year, rating) and need to dynamically return a specific child. What would be the most resource efficient way to do this?
I am thinking that maybe parentgameobject.transform.Find("ChildName")
isn't such a bad idea in this use case, since from what I understand, it would only loop the 5 child objects and return on the first match, and not the whole scene hierarchy (true?), but I would like to hear opinions and suggestions on this.
Answer by Inanoglu · Oct 05, 2020 at 08:48 AM
My suggest is use tags. Give tags to your objects and find them
Thank you, I forgot to mention that there are more than 1000 parents (I updated the question now). But I did some investigating and it seems there is no FindChildrenWithTag equivalent. But I did find an extension someone did at: https://gist.github.com/Ashwinning/551ab77201e89a352bff
Since FindWithTag will loop through all tags, I suppose this is needed in this use case.
Question in this is, is this more efficient than
parentgameobject.transform.Find("ChildName")
public static Transform[] FindChildrenWithTag(this Transform trans, string tag)
{
Transform[] kids = trans.GetComponentsInChildren<Transform> ();
Transform[] kidsWithTag = new Transform[] {};
foreach (Transform kid in kids)
{
if (kid.tag == tag)
{
kidsWithTag [kidsWithTag.Length] = kid;
}
}
return kidsWithTag;
}