List all children in array?

Could someone give me and example to find all the children of an object and list them in an array?

If you want to add the entire list of gameObject children to an array use this method.

Unfortunately gameobject.childCount / gameObject.GetChild() don’t exist, however it does for transform. so we can use that method to find the gameObjects and add them to the array.

private GameObject[] m_gameObjects;
        
private void Start()
{
    m_gameObjects = new GameObject[transform.childCount];
    for (int i = 0; i < transform.childCount; i++)
    {
        m_gameObjects *= transform.GetChild(i).gameObject;*

}
}
I hope this helps :slight_smile:

public GameObject thingy;
public int count;
public GameObject thingyparts;
public void Start(){
count=0;
foreach(Transform i in thingy.transform){
count++;
}
thingyparts = new GameObject[count];
count=0;
foreach(Transform i in thingy.transform){
thingyparts[count]=i.gameObject;
count++;
}

	}

@JamBroski
@toddisarockstar

Not sure if it work, but probably something like this:

using UnityEngine; // Duh.
using System.Collections.Generic; // To Use List because List is awesome :)

public class StupidlySimpleFunction {
    public static GameObject[] getChildren(GameObject parent, bool recursive = false)
    {
        List<GameObject> items = new List<GameObject>();
        for (int i = 0; i < parent.transform.childCount; i++)
        {
            items.Add(parent.transform.GetChild(i).gameObject);
            if (recursive) { // set true to go through the hiearchy.
                items.AddRange(getChildren(parent.transform.GetChild(i).gameObject,recursive));
            }
        }
        return items.ToArray();
    }
}

You can call this function by just go StupidlySimpleFunction.getChildren(GameObject) since it’s static.

Set recursive to true if you want multiple layers, like children of children of children of a GameObject etc…

Transform implements IEnumerable, so you can cast it to a generic IEnumerableand use LINQ to handle it, which translates to this:

Transform[] allChildTransforms = transform.Cast<Transform>().ToArray();

public IEnumerable Children =>
GetComponentsInChildren()
.Where(t => t != transform)
.Select(t => t.gameObject);

Like this?