接上一篇:http://www.javashuo.com/article/p-ccyhllxl-ed.htmlhtml
除了Append類型對應的Consume/AppendStructuredBuffer還有一個Counter類型能夠進行計數操做。測試
那麼測試一下:ui
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ComputeShaderTest : MonoBehaviour { public ComputeShader computeShader; void Awake() { var kernelID = computeShader.FindKernel("CSMain"); var counterBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.Counter); counterBuffer.SetCounterValue(5); computeShader.SetBuffer(kernelID, "counter", counterBuffer); computeShader.Dispatch(kernelID, 1, 1, 1); var argBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments); ComputeBuffer.CopyCount(counterBuffer, argBuffer, 0); //經過這個方法拿到第一個數據。 int[] counter = new int[1] { 0 }; argBuffer.GetData(counter); int count = counter[0]; Debug.Log("count: " + count); argBuffer.Release(); counterBuffer.Dispose(); } }
computer shader:spa
#pragma kernel CSMain RWStructuredBuffer<int> counter; [numthreads(8, 1, 1)] void CSMain(uint3 id : SV_DispatchThreadID) { if (id.x == 1 || id.x == 2 || id.x == 3) { //counter.IncrementCounter(); counter.DecrementCounter(); } }
測試的是DecrementCounter最終打印2。code
另外須要注意,若是在同一個csmain裏同時進行加減操做則會報錯:htm
RWStructuredBuffers may increment or decrement their counters, but not both. at kernel CSMainblog