0

How do I find all children gameObjects of a parent (sub included: parent-child-children..) and assign it to a gameObject?

The below script finds all the children gameObjects of their current parent but does not find the sub children gameObjects of the found children.

public GameObject parent;
private GameObject AssignedChild;

 foreach (Transform eachChild in parent.transform)
        {
            if (eachChild.gameObject.tag == "TagOfTheObject")
            {
               //assign the tagged GameObject to "AssignedChild" GameObject
               AssignedChild = eachChild.gameObject;
            }

        }
  • Might be a good time for a recursive method. Check this post out (https://stackoverflow.com/questions/25304000/traversing-all-descendants-of-an-object) – Ryan Wilson Jun 27 '19 at 13:41
  • Also, a `GameObject` field holds a *single* object, if you want to store *all* of them, you will need an array or list. – Draco18s no longer trusts SE Jun 27 '19 at 13:46
  • @Draco18s no i only want to find single gameObject since I am assigning unique tags to each object and then assign each to each gameObject. –  Jun 27 '19 at 13:49
  • *`assign them to gameObject`* "them" is a plural noun. But if each object has a unique tag, [`GameObject.FindWithTag()`](https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html)? – Draco18s no longer trusts SE Jun 27 '19 at 13:52
  • Sorry I corrected it, assigning is not an issue. Finding sub and sub children gameObjects is the issue. My hierarchy is "Parent - child - children - subchildren- etc" –  Jun 27 '19 at 13:55
  • Just checking, Is there some reason to not just make AssignedChild public and then drag the thing you want to look up there in the editor? – gman Jun 27 '19 at 14:14
  • I can but I was looking for different approach since I will be attaching this script to multiple gameObjects :D –  Jun 27 '19 at 14:15

1 Answers1

0

I just had to add one line to find all the children gameObjects

public GameObject parent;
private GameObject AssignedChild;

 foreach (Transform eachChild in parent.GetComponentsInChildren<Transform>())
        {
            if (eachChild.gameObject.tag == "TagOfTheObject")
            {
               //assign the tagged GameObject to "AssignedChild" GameObject
               AssignedChild = eachChild.gameObject;
            }

        }