Unity中如何确保AppendStructuredBuffer追加元素数量超过32
问题根因
你遇到的问题核心是创建ComputeBuffer时没有指定对应AppendStructuredBuffer的缓冲类型,导致Append操作的内部原子计数器未正常工作,多线程写入时出现冲突,仅少量数据被成功写入。
修复步骤
- 1 创建ComputeBuffer时显式指定类型为
ComputeBufferType.Append - 2 每次写入前重置缓冲计数器,避免旧数据干扰(单次运行也建议加上)
- 3 读取数据前先获取缓冲内实际写入的元素数量,避免遍历到未写入的空数据位
修复后完整C#代码
int threads = 1; int testResults = threads * 8 * 8 * 8 * 2; // 第三个参数指定缓冲类型为Append,匹配Shader里的AppendStructuredBuffer ComputeBuffer results = new ComputeBuffer(testResults, sizeof(float) * 3, ComputeBufferType.Append); // 重置计数器,确保从0开始计数 results.SetCounterValue(0); noiseShader.SetBuffer(0, "result", results); noiseShader.Dispatch(0, threads, threads, threads); // 获取实际写入的元素数量 ComputeBuffer countBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.Raw); ComputeBuffer.CopyCount(results, countBuffer, 0); int[] countArr = new int[1]; countBuffer.GetData(countArr); int actualCount = countArr[0]; countBuffer.Release(); // 只读取实际写入的长度即可,也可以读全量但仅遍历到actualCount为止 Vector3[] test = new Vector3[actualCount]; results.GetData(test, 0, 0, actualCount); results.Release(); Debug.Log("实际写入元素数量 : " + actualCount); for(int i = 0; i < actualCount; i++) { Debug.Log("Test result at " + i + " : " + test[i] ); }
补充说明
你当前的Dispatch参数threads=1配合[numthreads(8,8,8)],总线程数确实是888=512,修复后可以得到完整的512条正确数据。如果后续要扩大Dispatch尺寸,只需要对应调大ComputeBuffer的初始化容量即可,只要容量大于等于总线程数就不会出现数据溢出丢失的问题。
内容的提问来源于stack exchange,提问作者Lilly
相关产品推荐
相关产品推荐

