Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question