【发布时间】:2021-09-27 12:29:32
【问题描述】:
我的问题很直接:将包含连续浮点数的字节流byte[] data 转换为表示网格顶点Vector3[] vertices 的向量数组。
到目前为止,这是我的方法(此处仅显示相关代码):
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);
}
这失败了,因为Buffer.BlockCopy() 仅适用于原始类型。当然我们可以直接复制到float[],但是如何在没有循环的情况下从float[] 转换到Vector3[]?
基本上,我想避免遍历网格的所有顶点(以及法线、三角形……),因为我的字节流中已经有了正确排序的数据。我只是想创建具有正确大小的对象并复制(或引用)数据。
编辑:Found this answer to a similar question: 这是几年前的事了。它仍然是我问题的最佳答案吗?使用不安全代码有什么注意事项?
【问题讨论】:
-
float[] to Vector3[] without a loop我不认为你可以,因为我们真的不知道 Unity 是如何将这些值存储在内存中的 -
您可能想查看new Mesh API using Unity's JobSystem,虽然.. JobSystem 使用
NativeArray,您可以在它们上使用Reinterpret<T>在集合类型之间进行转换 -
@derHugo 感谢您的建议,下面的答案也将我带到了 NativeArrays! :)