I'm trying to write a compute shader with Unity that generates mesh data (vertices, normals, uvs) for a voxel terrain. Thus, I have a custom struct defined as follows :
[StructLayout(LayoutKind.Sequential, Pack = 0)]
private struct VertexData
{
public Vector3 position;
public Vector3 normal;
public Vector2 uv;
}
Then, I'm creating a ComputeBuffer for the ComputeShader as follows :
vecterDataCBuf = new ComputeBuffer(ChunkSize * ChunkSize * ChunkSize, sizeof(VertexData));
I'm getting the CS0233 error indicating the I can't use the sizeof operator on my custom struct to provide the stride for the compute buffer, despite the packing attribute I added.
So my question is, how can I get the size of my struct without hard coding it ? Thank you.
sizeof
only works for predefined types unless you're in an unsafe
context. From the reference on sizeof
:
The following table shows the constant values that are substituted for sizeof expressions that have certain built-in types as operands. [...] For all other types, including structs, the sizeof operator can be used only in unsafe code blocks.
So wrap your call in unsafe
like:
int sizeOfVertexData;
unsafe
{
sizeOfVertexData = sizeof(VertexData);
}
You'll also have to enable unsafe code. In Unity it's apparently a checkbox.
You can compute the total size of your struct by adding each property size.
A Vector3 is equivalent to 3 floats. A Vector2 is equivalent to 2 floats.
//int stride = sizeof(position) + sizeof(normal) + sizeof(uv)
//int stride = sizeof(Vector3) + sizeof(Vector3) + sizeof(Vector2)
int stride = sizeof(float) * 3 + sizeof(float) * 3 + sizeof(float) * 2
You don't need unsafe stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With