RaycastHit.triangleIndex Frame Drop!

I’m working on wheel surface detection for some cars. I’ve got everything working perfectly but when I run the scene, there’s a very noticeable frame drop.

Here’s the snippet of code that handles surface detection :

private Texture2D GetSurfaceTexture(){

Texture2D texture = null;

if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hit, 0.2f + (GetComponent<WheelCollider>().radius))){

if(hit.collider.gameObject.GetComponent<Renderer>()){

MeshFilter meshFilter = (MeshFilter)hit.collider.GetComponent(typeof(MeshFilter));
Mesh mesh = meshFilter.mesh;
int totalSubMeshes = mesh.subMeshCount;
int[] subMeshes = new int[totalSubMeshes];
           
for(int i = 0; i < totalSubMeshes; i++){
subMeshes[i] = mesh.GetTriangles(i).Length / 3;
}
           
int hitSubMesh = 0;
int maxVal = 0;
           
for(int i = 0; i < totalSubMeshes; i ++){
maxVal += subMeshes[i];

if(hit.triangleIndex <= maxVal - 1){
hitSubMesh = i + 1;
break;
}
}

texture = (Texture2D)hit.collider.gameObject.GetComponent<Renderer>().materials[hitSubMesh-1].mainTexture;
}
}

return texture;
}

Basically, what I do is get the triangle the ray hit and then return it’s material’s main texture.

I get an average of 40 fps if I call this function and an average of 60 fps if I don’t.

Does anyone know what I could be doing wrong or how to fix this?

Thanks.

I’m assuming you’re doing this for friction or sound purposes: You’re waaaaaaaaay better off just adding some sort of description to the GameObject itself and pulling that information instead, whether you tag it as Asphalt / Dirt / Grass or create some sort of enum and throw it in a component.

Hey @GroZZleR , thanks for your reply.

Yeah, I’m doing it for friction, sound & particle purposes.

I wish it was that easy but it isn’t. Most meshes use multiple materials on the same mesh so to get the current texture the wheel is on, I need to find the material that the triangle uses and get it’s material’s main texture.

I never knew this would drop the framerate by about 10 - 20.

Anyone know if there an efficient way of getting this done?

Thanks.