Search Unity

Accessing various elements from a raw vertex buffer

Discussion in 'Entity Component System' started by pk1234dva, Jan 15, 2022.

  1. pk1234dva

    pk1234dva

    Joined:
    May 27, 2019
    Posts:
    84
    Is the following code valid? It's a sample of how I'm trying to get the position of the vertex with index 13, from the raw vertex buffer.

    I'm assuming the first stream consists of 3 floats32 (positions) and 2 floats16 (uv), hence 16 bytes per vertex (only working with the 0th vertex buffer here).

    Code (CSharp):
    1. int bytesPerVertex = 16;
    2. int bytesPerPosition = 4; // could be 2 if float16
    3. int vertexIndex = 13; // index I want to get the position for
    4.  
    5. var vertexBuffer = meshData.GetVertexData<byte>(0);
    6. byte* vertexBufferPtr = (byte*)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vertexBuffer);
    7.  
    8. byte* ptr = vertexBufferPtr + 13 * bytesPerVertex;
    9. float xPosition = ((float*)tempPointer)[0];
    10. ptr += bytesPerPosition;
    11. float yPosition = ((float*)tempPointer)[0];
    12. ptr += bytesPerPosition;
    13. float zPosition = ((float*)tempPointer)[0];
    Is there a better way of doing this? Just reinterpreting the array as NativeArray<float> works in most cases, but there's no guarantee the array only consists of 4byte elements, and in that case I need a more general approach.