C# Get Childs to add in array

Hello Everyone,

i’m new to unity and C#, and after 2 weeks of read and code i’m first time totally stuck. Today i wanted to implement that my game is able to convert a GameObject with lots of subGOs to a newmesh. But after hours of google around and read similar guestions here in the forum i’m more than confused now.

  • What i have is an GO with lots of other GOs (meshes) in a complex hierarchy.

  • What i need is and array with every single GO that has a mesh.

I’ve played around with foreach transform etc… but i don’t get it. Afterwards i would like to run this code:
link text

Some hints or lines would be awesome. :slight_smile:

I suppose that you want to fill this array in the example?

public GameObject[] objectsToCombine;

Getting all child GameObject is not straightforward, and often not needed. Unity has no Methods to get a list of child GameObjects, only methods to get Components from childs (a transform GetChild method also returns a Transform which is a Component). The difference is that the GameObject is the thing you see in the hierarchy. The Components are displayed in the Inspector. Which means that each GameObject has one or more Components and each Component has one GameObject.

You probably want to search for either meshFilter or Renderer. Since we want all GameObjects with these components

The code to get a list of them is simply:

MeshFilter[] list = GetComponentsInChildren<MeshFilter>();

Now note that instead of a GameObject, we retrieve a list Of MeshFilters. But like every component, we could call the gameobject property if we need it. so you can probably use this list instead of your list of gameobjects.

for (int i = 0; i < list.Length; i++)
{
    Debug.Log(list*.gameObject.name);*

}
If you really want a list of GameObjects through, you could use something like this, you use this in the same way as you use GetComponentsInChildren (Though this will be slightly slower obviously)
public GameObject[] GetChildGameObjectsWithComponent() where T : Component
{
T[] componentList = GetComponentsInChildren();
GameObject[] returnList = new GameObject[componentList.Length];
for (int i = 0; i < componentList.Length; i++)
{
returnList = componentList*.gameObject;*
}
return returnList;
}

Yey, Thank you troien. Yes, that is what i was looking for. And, finally, after a few hours if found it just a minute ago myself. But thanks alot for your time!

MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
objectsToCombine = new GameObject[meshFilters.Length];
int i = 0;

while (i < meshFilters.Length) {
	objectsToCombine _= meshFilters*.gameObject;*_

* i++;*
}