Using foreach while looking for tag in children
Hello human beings. I'm tring to find the "clothes" tag on a child of the gameobject running the script.
CODE:
Color m_color = new Color (red, green, blue);
foreach (Transform child in transform) {
if (child.CompareTag ("Clothes")) {
print (child);
print (m_color);
GetComponent<Renderer> ().material.color = m_color;
My code doesn't print anything. Help pls.
Ethan
Is it an immediate child? The sample code provided won't search for a child of a child
Does it actually have the tag "Clothes" set?
Answer by Yerendi · Aug 15, 2016 at 10:05 AM
To iterate all childs (not only immediate childs) you can use recursive method:
public GameObject MyGameObject;
public string TagToFind;
private void Start()
{
GameObject myChild = GetChildWithTag(MyGameObject, TagToFind);
if (myChild != null)
{
Debug.Log(string.Format("Found child with tag {0}", TagToFind));
}
else
{
Debug.Log(string.Format("There is no child with tag {0}", TagToFind));
}
}
private GameObject GetChildWithTag(GameObject gameObject, string tagToFind)
{
foreach (Transform child in gameObject.transform)
{
if (child.gameObject.CompareTag(tagToFind))
{
return child.gameObject;
}
if (child.childCount > 0)
{
return GetChildWithTag(child.gameObject, tagToFind);
}
}
return null;
}
Your method will end at the first child that has children. The second IF should look like this ins$$anonymous$$d:
if (child.childCount > 0)
{
GameObject found = GetChildWithTag(child.gameObject, tagToFind)
if (found != null)
return found;
}
You can get all children of a gameobject (including itself and children from children) with
Transform[] l_children = GetComponentsInChildren<Transform>();
Your answer
![](https://koobas.hobune.stream/wayback/20220612090839im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Trying to iterate through a prefab to access its child objects 1 Answer
How do I stop a child from taking the parent's tag? 1 Answer
Change layer for unparented child. 0 Answers
Comparing an ArrayList to the current object in an Arraylist being checked through a forEach Loop? 0 Answers
What to do for many comparison operations in foreach loop? 0 Answers