Hello,
I am testing a simple compute shader I wrote in Unity 2021.1.20f1 (URP) and have encountered an issue. Below is MonoBehaviour and ComputeShader, so I am hoping someone will be able to detect what’s wrong.
// MONOBEHAVIOUR
using UnityEngine;
public class ComputeShaderTest : MonoBehaviour
{
[SerializeField] private ComputeShader computeShader;
[SerializeField] private bool validate = false;
private ComputeBuffer myBuffer;
private int[] validationArray;
private void Awake()
{
validationArray = new int[5];
myBuffer = new ComputeBuffer(5, sizeof(int), ComputeBufferType.Structured, ComputeBufferMode.SubUpdates);
var writeBuffer = myBuffer.BeginWrite<int>(0, 5);
for (int i = 0; i < 5; i++)
{
writeBuffer[i] = 0;
}
myBuffer.EndWrite<int>(5);
int kernelIndex = computeShader.FindKernel("Start");
computeShader.SetBuffer(kernelIndex, "MyBuffer", myBuffer);
}
private void Update()
{
int kernelIndex = computeShader.FindKernel("Start");
computeShader.Dispatch(kernelIndex, 1, 1, 1);
if (validate)
{
myBuffer.GetData(validationArray);
for (int i = 0; i < validationArray.Length; i++)
{
Debug.Log(validationArray[i]);
}
validate = false;
}
}
private void OnDestroy()
{
myBuffer.Release();
}
}
//COMPUTE SHADER
#pragma kernel Start
RWStructuredBuffer<int> MyBuffer;
[numthreads(5,1,1)]
void Start (uint3 id : SV_DispatchThreadID)
{
MyBuffer[id.x] = 1;
}
ComputeShader does not seem to be dispatched or RWStructuredBuffer is not being written to, because Debug.Log returns 0, which are set at buffer initialization. ComputeShader is running each frame, but no change to data is detected.
Actual Result: Five 0’s are logged to console when validate flag is checked in inspector.
Expected Result: Five 1’s are logged to console indicating successful write operation from compute shader.
NOTE: ComputeShader/MonoBehaviour does not have any compilation errors, as well as no runtime exceptions.
NOTE: I am aware of thread count being low, and not efficient on GPU, but optimization is not the issue I am trying to solve.
Thank you.
