Getting triangles for all submeshes

I’m trying to get all the triangles from a mesh to work out the vertex colour at the point where a raycast has hit a mesh. This will be happening every frame so I want to be careful about allocating.

The obvious way to do this seems to be to call mesh.triangles and then use the triangleIndex from my raycast hit to index into that, before using the triangle indicies to get the vertex colour from the colour buffer. Unfortunately calling mesh.triangles will allocate a new array every time. Ideally I would use mesh.GetTriangles() instead so that I could pass in a buffer that could be reused every frame, but to use that I need to know which submesh I have hit and as far as I’m aware there is no way to know that.

Internally, mesh.triangles appears to use a submesh index of -1, but GetTriangles() has an explicit check to make sure your submesh index is 0 or greater so I can’t just pass -1 in either. Is there really no way to get the full triangle list without allocating? Otherwise it seems like the only option is to only support meshes with a single submesh.

Don’t know if that is the best way to do it but you can probably go through the submesh descriptors first and find the one that contains the triangle index by checking indexStart and indexCount.

Untested pseudo code:

int subMeshIndex = -1;
for (int i = 0; i < mesh.subMeshCount; ++i)
{
    Rendering.SubMeshDescriptor subMeshDesc = mesh.GetSubMesh(i);
    if (subMeshDesc.indexStart >= triangleIndex * 3 &&
subMeshDesc.indexStart + subMeshDesc.indexCount < triangleIndex * 3)
   {
       subMeshIndex = i;
       break;
   }
}

Alternatively, if you could encode the information you need in texCoord2, you’d get it immediately in the RayCastHit struct (assuming that you don’t need texCoord2 for light map uv’s).

1 Like

Thanks, that was the information I needed. It would probably be nice to have access to the full triangle list at once without allocating, but check which submesh I’m in works fine in this case. Putting the information into texcoord2 wouldn’t have worked here because we are already using that for something else, but I think I’ll try to do it that way in the future. Avoiding the cost of reading back all the mesh data would definitely be preferable, just hard to pivot to doing it that when if you already have a lot of art assets made

1 Like