- Home /
Mesh.CombineMeshes does not work when mergeSubMeshes=false
In my script, I am trying to combine all objects that share the same material color into individual submeshes on a merged GameObject. So far, I'm getting extremely frustrated with the Mesh.CombineMeshes "mergeSubMeshes" flag.
It appears that when I set this flag to "false," I end up with only one visible submesh, and the inspector for the GameObject says, "This renderer has more materials that the Mesh has submeshes." I'm grateful for any help!
private Dictionary<Color32, Material> materialsByColor = new Dictionary<Color32, Material>();
GameObject CombineMeshes (List<GameObject> gameObjects){
var numGameObjects = gameObjects.Count;
var combinedGameObject = (GameObject)GameObject.Instantiate(combinedMesh);
var combinedMeshFilter = combinedGameObject.GetComponent<MeshFilter>();
var combineInstances = new CombineInstance[numGameObjects];
var colors = new List<Color32>(materialsByColor.Keys);
GameObject obj;
CombineInstance combineInstance;
MeshFilter objMeshFilter;
int submeshIndex;
for(int i = 0; i < numGameObjects; i++) {
obj = gameObjects[i];
combineInstance = combineInstances[i];
objMeshFilter = obj.GetComponent<MeshFilter>();
combineInstance.mesh = objMeshFilter.sharedMesh;
combineInstance.transform = objMeshFilter.transform.localToWorldMatrix;
// I want to put each object in a submesh with objects of the same material
submeshIndex = colors.IndexOf(obj.GetComponent<Renderer>().material.color);
// Prints exactly what I expect.
print (submeshIndex);
combineInstance.subMeshIndex = submeshIndex;
}
combinedMeshFilter.mesh = new Mesh();
combinedMeshFilter.mesh.CombineMeshes(combineInstances, false, true);
combinedGameObject.GetComponent<Renderer>().materials = new List<Material>(materialsByColor.Values).ToArray();
// Prints an unreasonably low number, and it appears only one submesh is rendering
print(combinedMeshFilter.sharedMesh.subMeshCount);
return combinedGameObject;
}
Answer by Pixelome · Oct 30, 2017 at 10:08 PM
I know it has been a while but I'm hoping that this will help somebody else since I lost a few hours trying to figure out why this is happening.
When using "mesh.CombineMeshes(combineInstances, false, true);" the mesh renderer needs to have a material for each submesh. This is why only the first submesh is visible, because there are no materials for other submeshes.