From the doc’s the definition function GetData (data : System.Array) : void doesn’t return a value but fills the source data array with the values.
You pass in an empty data array and it gets filled up. After the call is finished the array now contains the compute data.
NOTE: I have yet to actually test this in code and have no personal experience with DX11 compute shaders. The information provided above was gleaned solely from the Docs and might be in error.
YMMV
It seems like I’m a little bit confused.
I’m trying to compute an array ( fill with noise values ) via a compute shader ( or shader ) and to retrieve it on the cpu via ComputeBuffer.GetData.
But I’m stuck here. I was looking for a sample to start with but I can’t find anything.
using UnityEngine;
using System.Collections;
public class ComputeShader_test : MonoBehaviour {
public ComputeShader compute;
public ComputeBuffer buffer;
public int[] cols;
void Start () {
var mesh = GetComponent<MeshFilter>().mesh;
int n = mesh.vertexCount;
///
buffer = new ComputeBuffer (n, 16);
///
cols = new int[n];
///
for (int i = 0; i < n; ++i)
cols[i] = 0;
buffer.SetData (cols);
///
compute.SetBuffer(compute.FindKernel ("CSMain"),"bufColors", buffer);
///
compute.Dispatch(0,4,4,1);
///
buffer.GetData(cols);
Debug.Log (cols[0]);
}
compute shader code :
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain
StructuredBuffer<int> bufColors;
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
bufColors[0] = 2;
}
I’m expecting cols[0] to return 2 as it is set in the compute shader. But it return the original value ( 0 ).
What am I missing to simply get back data from computebuffer ?
Sorry for reviving an old thread, but I have a similar problem with compute buffers. I use the exact same code as sepion, but instead of just having an int in a raw buffer, I use a struct which contains a single int with the default buffer type. Is there something special I must do to work with structs in compute buffers?
Well, right now, I use computeShader.GetData() on an int array, like sepion did. However, my buffer contains a struct instead of a simple int. This struct contains a single “int” variable though.
So my question is, what should be the parameter of GetData() if my structuredBuffer contains a struct?
I’ll need to investigate this further. Nothing seems to work for me. If I put the exact same script as sepion, with a RWStructuredBuffer, it doesn’t work either, so I’m pretty confused here… Anyways, thanks for your help.