Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to get verticies by triangle index?

Discussion in 'Physics' started by unity_207ECD6E61F6914F7CA2, Sep 13, 2022.

  1. unity_207ECD6E61F6914F7CA2

    unity_207ECD6E61F6914F7CA2

    Joined:
    Jan 26, 2022
    Posts:
    4
    Hi. Raycast and sweep queries return triangle index among other things. I would like to use that index to get actual vertices of the mesh.

    The first thing I tried is what documentation suggests here: https://docs.unity3d.com/ScriptReference/RaycastHit-triangleIndex.html . But as it turns out, in this example the entire mesh data is re-allocated and copied every frame. I then found a non-allocating API, but it still copies the data. There is no way I can afford that.

    So is there any way to get three vectors from the actual underlying data of mesh collider? Or am I supposed to manually cache every single mesh data in managed memory to have sensible performance?

    P.S. I have also found this api: https://docs.unity3d.com/ScriptReference/Mesh.AcquireReadOnlyMeshData.html which looks like what I need. But I do not see a way to convert triangle index into vertex indices. Am I missing something?
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,191
    You get both index (triangle) and vertex buffer arrays. Take any index from the index buffer, that will be the index of the vertex in the vertex buffer.

    pseudocode:
    Code (CSharp):
    1. var vertex = vertexbuffer[indexbuffer[i]];


    A vertex is a (local) position plus additional data such as normal, tangent, color, uv and so on that may vary depending on the vertex buffer parameters.

    But I get the feeling that maybe you're overcomplicating things. What is it that you're trying to accomplish in the end? Perhaps there are easier ways to achieve what you want.
     
  3. unity_207ECD6E61F6914F7CA2

    unity_207ECD6E61F6914F7CA2

    Joined:
    Jan 26, 2022
    Posts:
    4
    Ah, I think I got it. Basically "index" means "triangle index" when it comes to triangle meshes. And I should be able to get triangle data from "index" array.

    All I want is to get accurate surface normal (for a mesh which does not have normals pre-calculated).
     
  4. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,191
  5. unity_207ECD6E61F6914F7CA2

    unity_207ECD6E61F6914F7CA2

    Joined:
    Jan 26, 2022
    Posts:
    4
    No, I am using cross product to calculate normals. This part I have no problems with. The only problem is getting those 3 vertices in the first place, without allocating 100500 bytes every frame :)