Home > Back-end >  How to get a array of Vector3 from a byte stream?
How to get a array of Vector3 from a byte stream?

Time:09-27

My problem is rather straight forward: Convert a bytestream byte[] data containing continuous floats into an array of vectors representing vertices of a mesh Vector3[] vertices.

Here is my approach so far(only relevant code shown here):

public void SetReconstructedMeshFromDataStream(byte[] data)
{
    int vertexBufferSize = BitConverter.ToInt32(data, 0);

    Mesh mesh = new Mesh();
    // 12 is the size of Vector3:
    mesh.vertices = new Vector3[vertexBufferSize / 12];  
    // srcOffset = 12, because that is the size of the header in the data buffer:
    Buffer.BlockCopy(data, 12, mesh.vertices, 0, vertexBufferSize); 
}

This fails, since Buffer.BlockCopy() only works with primitive types. Of course we could just copy to a float[], but the how to cast from float[] to Vector3[] without a loop?

Basically I want to avoid having to loop over all the vertices of my mesh (and normals, triangles,...), since I already have the correctly ordered data in my bytestream. I simply want to create the objects with the correct size and copy (or reference) the data.

EDIT: Found this answer to a similar question: This is a few years old. Is it still the best answer to my question? Any considerations using unsafe code?

CodePudding user response:

Have done something quite similar once to transfer vectors from a C dll to an array of vectors. I do not recall the exact code, but it involved the Unity Collections package. That one provides a series of native datatypes including NativeArray that has a Reinterpret method which directly allows to reinterpret the type into another one. In my case, I already had a series of floats, but it might work directly from bytes as well.

That said, do you have control over the code that generates the byte stream? Because if you are writing your own native plugin, it is possible to get a handle to the mesh vertices and directly manipulate those on the DLL side which is likely another bit faster. The official native rendering plugin example in Unity's github demonstrates this.

  • Related