Search Unity

RaycastHit.triangleIndex Frame Drop!

Discussion in 'Scripting' started by Ian094, Jul 31, 2015.

  1. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    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 :

    Code (CSharp):
    1. private Texture2D GetSurfaceTexture(){
    2.  
    3. Texture2D texture = null;
    4.  
    5. if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hit, 0.2f + (GetComponent<WheelCollider>().radius))){
    6.  
    7. if(hit.collider.gameObject.GetComponent<Renderer>()){
    8.  
    9. MeshFilter meshFilter = (MeshFilter)hit.collider.GetComponent(typeof(MeshFilter));
    10. Mesh mesh = meshFilter.mesh;
    11. int totalSubMeshes = mesh.subMeshCount;
    12. int[] subMeshes = new int[totalSubMeshes];
    13.            
    14. for(int i = 0; i < totalSubMeshes; i++){
    15. subMeshes[i] = mesh.GetTriangles(i).Length / 3;
    16. }
    17.            
    18. int hitSubMesh = 0;
    19. int maxVal = 0;
    20.            
    21. for(int i = 0; i < totalSubMeshes; i ++){
    22. maxVal += subMeshes[i];
    23.  
    24. if(hit.triangleIndex <= maxVal - 1){
    25. hitSubMesh = i + 1;
    26. break;
    27. }
    28. }
    29.  
    30. texture = (Texture2D)hit.collider.gameObject.GetComponent<Renderer>().materials[hitSubMesh-1].mainTexture;
    31. }
    32. }
    33.  
    34. return texture;
    35. }
    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.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    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.
     
  3. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    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.