How to use submeshes?

Really easy question, I am very new to Unity. I can’t seem to use a submesh for some reason? I looked at the documentation for submesh count and using the SetTriangles method. I have googled around and while I find plenty of information on submeshes…but not information on the actual implementation.

Here are the steps I have taken:

  • Assigned 2 materials to my mesh renderer.
  • I set the submesh count:
mesh = GetComponent<MeshFilter> ().mesh;
mesh.subMeshCount = 2;
  • Populate a triangle list for each material
  • Set triangles to the mesh:
mesh.SetTriangles(dirtTriangles.ToArray(), 0);
mesh.SetTriangles(stoneTriangles.ToArray(), 1);

And BOOM, I get this when I try to play test:

"Failed setting triangles. Submesh index is out of bounds. UnityEngine.Mesh:SetTriangles(Int32[ ], Int32[ ]). It sounds like it is bombing out when I try to set the triangle list. Double clicking the error takes me to my second SetTriangles line. So I must be missing a step here or something, what is going wrong?

SOLUTION:

My mesh is procedurally built, so when it needs to be updated I call mesh.clear(). This was also clearing submesh data and submesh count, so I moved some assignments around and that works fine now.

2 Likes

Thanks !
I’m having the same problem. Good that you found the solution !

This should be indicated in the documentation of subMeshCount.

Definitely. At least as a “See Also” link. Is there a documentation maintainer on board :)?