2
\$\begingroup\$

I have an empty object that contains multiple children each containing their own child objects. I want to get a list of all the objects containing a specific tag but i don't know the depth of each child object. The following solution only returns the children that have the tag.

foreach (Transform child in city)
        {
            if (child.CompareTag("Zone"))
                buildings.Add(child);
        }
\$\endgroup\$
2
  • \$\begingroup\$ It's not clear what you are asking. \$\endgroup\$
    – Joza100
    Jul 31, 2018 at 14:52
  • 2
    \$\begingroup\$ When the objects you want to find also happen to have some component in common, then you could use GetComponentsInChildren. \$\endgroup\$
    – Philipp
    Jul 31, 2018 at 16:04

1 Answer 1

3
\$\begingroup\$

You could try something like this.

public List<GameObject> GetChildrenWithTag(GameObject obj)
{
    var childrenWithTag = new List<GameObject>();
    var allChildren = obj.GetComponentsInChildren<Transform>();
    foreach(var child in allChildren)
    {
        if(child.gameObject.CompareTag("Zone"))
        {
            childrenWithTag.Add(child.gameObject);
        }
    }
    return childrenWithTag;
}

I didn't test this code but I guess it works. You may also want to avoid to hard-code tags like you did with "Zone".

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .