This question follows from http://forum.unity3d.com/threads/207914-Batching-draw-calls
I have 80 gems of different colours, and I’m trying to get them all to render in the same draw call.
I discovered that any form of batching fails because my shader has 2 passes.
So now I am trying to combine the meshes of all 80 children into the parent.
So I turn off the renderer in each of the children (well, in the prefab from which all children are cloned), and put this code in the parent:
void Update( )
{
Component[] meshFilters = GetComponentsInChildren<MeshFilter>();
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
for (int i = 0; i < meshFilters.Length; i++ )
{
MeshFilter M_i = (MeshFilter)meshFilters[ i ];
combine[i].mesh = M_i.mesh;
combine[i].transform = M_i.transform.localToWorldMatrix;
//M_i.gameObject.active = false;
}
transform.GetComponent< MeshFilter >().mesh = new Mesh();
transform.GetComponent< MeshFilter >().mesh.CombineMeshes( combine ); // count <= std::numeric_limits<UInt16>::max()
transform.gameObject.active = true;
}
This has been adapted from Unity - Scripting API: Mesh.CombineMeshes
Code on that page wouldn’t run out of the box.
So this appears to work for a few seconds, but the triangle count goes through the roof and unity crashes. I’ve also been warned on the channel that using CombineMeshes every frame is a really bad idea.
EDIT: Note the error
// count <= std::numeric_limits<UInt16>::max()
transform.GetComponent< MeshFilter >().mesh.CombineMeshes( combine );
How to do this properly?
I’ve been told that the right way to do this would be to create the uber-mesh initially, and then each frame copy all of the child meshes into it Vertex by Vertex, Triangle by Triangle
How do I do this? Could someone point me towards some code?
EDIT: I may be able to adapt http://wiki.unity3d.com/index.php?title=MeshMerger