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.