How to correctly read data from a compute shader?

I’ve been trying to learn compute shaders in unity and i seem to be struggling a little bit. I just start with something small, changing a single Vector3 array, and I can’t seem to even get that to work. any ideas as to what could be wrong? Thanks in advance

c# code:

int amount = 1;
Vector3[] a = new Vector3[amount];
for (int i = 0; i < amount; i++) {
      a[i] = new Vector3(1f, 1f, 1f);
}
print(a[0]); //prints (1.0, 1.0, 1.0) as it should
ComputeBuffer buffer = new ComputeBuffer(amount, sizeof(float) * 3);
buffer.SetData(a);
movement.SetBuffer(0, "points", buffer);
cs.Dispatch(0, Mathf.CeilToInt(amount / 1024f), 1, 1);

buffer.GetData(a);
print(a[0]); //prints (1.0, 1.0, 1.0) when it should print (0.0, 0.0, 0.0)
buffer.Release();

shader code:

#pragma kernel CSMain

RWStructuredBuffer<float3> points;

[numthreads(1024,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    points[id.x] = float3(0., 0., 0.);
}
2 Likes

You are performing out of bounds write. Your amount is 1, but you are calling kernel with workgroup size 1024 which doesn’t perform any bounds checks. I wouldn’t expect it to cause output staying 1 1 1, but who knows. Doing something that may cause crashes may as well cause anything to happen. There might be other issues but fixing this wouldn’t hurt.

Did you solve this?

1 Like