List/Array of game objects

I am trying to get an array of game objects to then pass onto StaticBatchingUtility.Combine
(function Combine (gos : GameObject[ ], staticBatchRoot : GameObject) : void)

I have a bunch of game objects as a child to an object that I want to add to an array.
The way I have been trying to do it is to use GetComponents, however this tries to get the components of the children to that game object and not the game objects themselfs (from what I gather)

I am a noob programmer and this is what I got so far…

using UnityEngine;
using System.Collections;

public GameObject[] childArray;
public GameObject root;

public override void start()

childArray = root.GetComponents<GameObject>();
StaticBatchingUtility.Combine(childArray, root);

I am trying to get all the children of root to then use the same object for the root of static combine

Hi Scott,

I don’t think you can use the type of GameObject with GetComponent. Here’s the docs page in case you haven’t seen it. If it was me, I’d tag the children and use

var myArray = GameObject.FindGameObjectsWithTag("YOUR_TAG_HERE");

If you can’t use that method (maybe you’ve already got the tags set for something else?), I think you should be able to do it with GetChild

GameObject[] myArray = new GameObject[transform.childCount];
for (int i = 0; i<transform.childCount; i++)
	myArray[i] = transform.GetChild(i).gameObject;

There’s probably other ways to do it too.

Cheers,
Cahman

GetComponents doesn’t traverse children. Not sure if you can pass GameObject as T for GetComponent but Transform does work and will give you a similar result to just enumerating the Transform itself. So you’ve got a few options.

Enumerate Transform directly

List<GameObject> childArray = new List<GameObject>();
foreach (Transform t in root.transform)
{
    childArray.Add(t.gameObject);
}

Use GetChild as CahMan said - this might be handier because you don’t have to dump a List to an array before passing to the batching utility.

Alternately - just use the first overload of Combine that takes only the root GameObject.

Thanks guys! CahMan’s example works though I got a null reference exception once, need to look into that (the script worked and there was no problem) if it happens again them I will give Kelso’s implementation a try

The first method, not giving a list wouldnt work as I wanted the children and not the grandchildren to be batched (the grandchildren get better performance from dynamic batching in my situation)