简体   繁体   中英

Get child object its children objects into List

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
        }
    }

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM