Create input data for a compute shader in URP
Allocate a buffer that provides input data for a compute shader in a render pass.
Read time 2 minutesLast updated a month ago
When you run a compute shader in a render pass, you can allocate a buffer to provide input data for the compute shader.
Follow these steps:
-
Create a graphics buffer, then add a handle to it in your pass data. For example:// Declare an input bufferpublic GraphicsBuffer inputBuffer;// Add a handle to the input buffer in your pass dataclass PassData{ ... public BufferHandle input;}// Create the buffer in the render pass constructorpublic ComputePass(ComputeShader computeShader){ // Create the input buffer as a structured buffer // Create the buffer with a length of 5 integers, so you can input 5 values. inputBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 5, sizeof(int));}
-
Set the data in the buffer. For example:var inputValues = new List<int> { 1, 2, 3, 4, 5 };inputBuffer.SetData(inputValues);
-
Use therender graph API to convert the buffer to a handle the render graph system can use, then set the
ImportBufferfield in the pass data. For example:BufferHandleBufferHandle inputHandleRG = renderGraph.ImportBuffer(inputBuffer);passData.input = inputHandleRG; -
Use themethod to set the buffer as a readable buffer in the render graph system. For example:
UseBufferbuilder.UseBuffer(passData.input, AccessFlags.Read); -
In yourmethod, use the
SetRenderFuncAPI to attach the buffer to the compute shader. For example:SetComputeBufferParam// The first parameter is the compute shader// The second parameter is the function that uses the buffer// The third parameter is the RWStructuredBuffer input variable to attach the buffer to// The fourth parameter is the handle to the input buffercontext.cmd.SetComputeBufferParam(passData.computeShader, passData.computeShader.FindKernel("Main"), "inputData", passData.input);
Example
For a full example, refer to the example called Compute in the Universal Render Pipeline (URP) package samples.