Home > OS >  Get child object its children objects into List
Get child object its children objects into List

Time:03-02

I would like to add all objects that are way way nested inside my parent object to a List. The child objects are 100s of it which are way nested in multiple gameObjects. How do I add them to my list through script?

public List<GameObject> allObjs = new List<GameObject>();
public GameObject parent;

public void GetAllProducts () {
         foreach (Transform  g in parent.transform)
        {
            allObjs.Add(g.gameObject); //Gets only child but not its children
        }
    }

CodePudding user response:

GameObject is not a component so you cannot use with GetComponentXXXXX

You could use the Transform since it is the one component found on every game object:

public List<GameObject> allObjs = new List<GameObject>();
public GameObject parent;

public void GetAllProducts () 
{
    foreach (Transform tr in parent.GetComponentsInChildren<Transform>())
    {
        allObjs.Add(tr.gameObject); 
    }
}

Add true to GetComponentsInChildren to also find inactive objects:

 parent.GetComponentsInChildren<Transform>(true)
  • Related