CombineMeshes creates an ampty object

Hi,
I’m trying to combine a bunch of meshes into one. Copied and modified code from unity docs and it creates an empty mesh. The remark in the middle is a long code that instantiates prefabs and adds them as children to the island object - removed it here to make things more readable. What am I missing?

        GameObject  island = new GameObject("island" + ix.ToString() + iy.ToString());

       //Code that creates child objects

        MeshFilter[] meshFilters = island.GetComponentsInChildren<MeshFilter>();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];

       
        for (int i = 0; i < meshFilters.Length; i++)
        {
            combine[i].mesh = meshFilters[i].sharedMesh;
            combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
            meshFilters[i].gameObject.SetActive(false);
        }

        island.AddComponent<MeshFilter>();
        island.AddComponent<MeshRenderer>();
        island.transform.GetComponent<MeshFilter>().mesh = new Mesh();
        island.transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);

        island.AddComponent<MeshCollider>();
        island.transform.gameObject.SetActive(true);

There’s a lot of different ways to combine meshes. Most of the examples I have seen have one issue or another, and they ALL have required some extra engineering to make them actually work. For instance, some of them mis-handle source meshes that have more than one submesh, or otherwise mix up the materials.

If you want to track down what’s going wrong above, the only way is to strip down the input meshes to the simplest thing possible (two triangles being combined for example) and then debug it. I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

If you want to see my own implementation of a mesh combiner that works pretty well, check out my MakeGeo project and look for the CombineMeshes directory for some demo scenes:

MakeGeo is presently hosted at these locations:

https://bitbucket.org/kurtdekker/makegeo

Thank you for the detailed response Kurt but I know how to debug code, I’m posting here after hours of unsuccessful attempts…