Combining multiple meshes and keeping materials

I have several source meshes A, B and C. Each mesh has it’s own material and consists of single subMesh. Now, I want to create a new mesh which will contain 20 instances of each A, B and C meshes and I want this mesh consists of 3 subMeshes, i.e. one subMesh for all elements of each type. I use Mesh.CombineMeshes(…) for this purpose, but it combines all meshes into one subMesh or creates subMesh for every element (i.e. 60 subMeshes in my case). Both results are unacceptable.

Thank you!

There are several ways how one could use Mesh.CombineMeshes. If you pass “true” as second parameter it will combine all meshes into one submesh. This is the default setting. If you pass false each mesh will go into a seperate submesh.

CombineMeshes doesn’t care about materials on it’s own. It actually can’t since the material information is not available to the method since the materials belong to the renderer component.

The second parameter of CombineMeshes is ment to allow combining meshes with the same material into one mesh. So you have to do the combine process 3 times for your 3 groups of meshes, seperated by the material. Once you have the 3 combined meshes, one for each material, you could use the method again with the second parameter set to false. This final step will give you 1 mesh with 3 submeshes.

If you just want to combine static geometry in your level you can simply use the StaticBatchingUtility. It will take care of merging meshes with the same material. You literally have to do nothing but calling Combine() on a root object. All child objects will be merged into a single mesh. The individual MeshRenderers are automatically disabled. Once combined you can no longer move individual objects. Only the root object can still be moved.

One more suggestion for anyone coming here in the future if the other suggestions don’t suit you. You can do this very easily with the “Easy Mesh Combiner MT” plugin available in the Asset Store. Here is the link: Easy Mesh Combiner MT - Scene Mesh Merge, Atlasing Support & More | Game Toolkits | Unity Asset Store