As you can see in the picture below, or attachment, after combining my meshes I have a materials array of 100 with duplicate Materials.
I have the feeling that is not how it is supposed to be.
I followed some examples I found here on the forum, modified it a little for my purposes, but can’t find what causes it, or rather it is the only way I got it working.
Here is the code I am using:
static void CombineMeshes(List<GameObject> gameObjects,int xChunk,int zChunk)
{
//Collect all Materials out of 6 I am using that are used in this chunk
//One chunk could be only Grass Material
List<Material> hasMaterial = new List<Material>();
foreach(GameObject g in gameObjects)
{
Material mat = g.GetComponent<MeshRenderer>().material;
if (!hasMaterial.Contains(mat))
{
hasMaterial.Add(mat);
}
}
//Collect all Meshes by Material
//Each element of the array is a list/collection of meshes with the same material
List<CombineInstance>[] collectionCombine = new List<CombineInstance>[hasMaterial.Count];
Material[] materials = new Material[hasMaterial.Count];
materials = hasMaterial.ToArray();
for(int m = 0; m < materials.Length; m++)
{
collectionCombine[m] = new List<CombineInstance>();
foreach(GameObject g in gameObjects)
{
if(materials[m].name == g.GetComponent<MeshRenderer>().material.name)
{
CombineInstance combine = new CombineInstance();
combine.mesh = g.GetComponent<MeshFilter>().mesh;
combine.subMeshIndex = 0;
combine.transform = Matrix4x4.identity;
collectionCombine[m].Add(combine);
}
}
}
//Combine all meshes by (with same) Material
List<GameObject> final = new List<GameObject>();
for(int m=0; m< materials.Length; m++)
{
GameObject g = new GameObject();
g.AddComponent<MeshFilter>();
g.AddComponent<MeshRenderer>();
g.GetComponent<MeshRenderer>().material = materials[m];
g.GetComponent<MeshFilter>().mesh = new Mesh();
g.GetComponent<MeshFilter>().mesh.CombineMeshes(collectionCombine[m].ToArray());
final.Add(g);
}
//Combine all Combined Meshes
List<CombineInstance> finalCombine = new List<CombineInstance>();
foreach (GameObject g in final)
{
CombineInstance combine = new CombineInstance();
combine.mesh = g.GetComponent<MeshFilter>().mesh;
combine.subMeshIndex = 0;
combine.transform = Matrix4x4.identity;
finalCombine.Add(combine);
}
GameObject chunk = new GameObject("Chunk_" + xChunk.ToString() + "_" + zChunk.ToString());
chunk.AddComponent<MeshFilter>();
chunk.GetComponent<MeshFilter>().mesh = new Mesh();
chunk.AddComponent<MeshRenderer>();
chunk.GetComponent<MeshRenderer>().materials = materials;
chunk.GetComponent<MeshFilter>().mesh.CombineMeshes(finalCombine.ToArray(), false);
chunk.AddComponent<MeshCollider>().sharedMesh = chunk.GetComponent<MeshFilter>().mesh;
foreach(GameObject g in gameObjects)
{
GameObject.DestroyImmediate(g);
}
foreach(GameObject g in final)
{
GameObject.DestroyImmediate(g);
}
}
How can I do this better without getting an Materials array of size 100 with duplicate Materials?