How to find child objects with a specific tag ?

Hello Everyone and Happy Holidays,

I wrote this small function which iterates over each child objects and checks whether it has an active tag. I would like to return the object that has an active tag, however, it returns the following error:

Assets/Game_Manager.cs(135,23): error CS0161: 'Game_Manager.getActive()': not all code paths return a value

Any idea on whats going on wrong here ?

 public GameObject getActive()
    {
        //return GameObject.FindGameObjectsWithTag("Active")[0];
        foreach (Transform child in parent.transform)
        {
            if (child.tag == "Active")
            {
                return child.gameObject;
            }
        }
    }

Your idea should work with some minor tweaks. What is the ā€œcā€ variable supposed to be doing, for instance?

This should work:

GameObject FindChildWithTag(GameObject parent, string tag) {
   GameObject child = null;

   foreach(Transform transform in parent.transform) {
      if(transform.CompareTag(tag)) {
         child = transform.gameObject;
         break;
      }
   }

   return child;
}
5 Likes

It was a counter, I however removed it in a recent edit of the original post. Let me try and understand what your method does.

ty

1 Like