H
H
HeySleare2021-05-13 21:46:59
Unity
HeySleare, 2021-05-13 21:46:59

How to search among child objects by tag in unity?

I have many different torches, lamps and candelabra where the light object is a child. I need to turn off the lights in these objects. Right now it's done like this
transform.FindChild("CandleLight").gameObject.SetActive(true);
but this is not convenient, since the names of the child objects are different, and I need to turn it off with the "Light" tag

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GFX Data, 2021-05-14
@ShockWave2048

As an extension method for the Transform class:

public static void AddDescendantsWithTag(this Transform parent, string tag, List<GameObject> list)
{
      foreach (Transform child in parent)
      {
            if (child.gameObject.tag == tag)
            {
                list.Add(child.gameObject);
            }

            AddDescendantsWithTag(child, tag, list);
      }
}
// Применяем:
List<GameObject> list = new List<GameObject>();
transform.AddDescendantsWithTag("Light", list);
list.ForEach((go)=>{go.SetActive(true);});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question