Documentation

Unity Engine

Unity Engine

Read input data into a compute shader in URP

Allocate a buffer that reads input data into a compute shader in a render pass.
Read time 2 minutesLast updated a month ago

To read input data into the compute shader, do the following:
  1. Create a graphics buffer using
    CreateBuffer
    , then add a handle to it in your pass data. For example:
    // Declare a buffer handleBufferHandle m_InputBufferHandle;// Add the handle to your pass dataclass PassData{ public BufferHandle input; // ...}// Create the buffer in RecordRenderGraphpublic override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData){ // Create the input buffer as a structured buffer of 20 ints BufferDesc desc = new BufferDesc { name = "InputBuffer", count = 20, stride = sizeof(int), target = GraphicsBuffer.Target.Structured }; m_InputBufferHandle = renderGraph.CreateBuffer(desc);}
  2. Create placeholder data in the buffer to read from for this example:
    // Placeholder input data for the compute shaderprivate List<int> inputData = new List<int>();// Initialize in the render pass constructorpublic ComputePass(){ for (int i = 0; i < 20; i++) { inputData.Add(i); }}
  3. Attach the buffer handle and data to the pass data.
    using (var builder = renderGraph.AddComputePass("ComputePass", out PassData passData)){ passData.input = m_InputBufferHandle; passData.bufferData = inputData;}
  4. Use the
    UseBuffer
    method to declare the buffer as an input of this pass in the render graph system. For example:
    builder.UseBuffer(passData.input, AccessFlags.Read);
  5. In your
    SetRenderFunc
    method, use the
    SetBufferData
    API to upload the input data to the buffer and the
    SetComputeBufferParam
    API to attach the buffer to the compute shader. For example:
    // Upload input data to the Render Graph buffercontext.commandBuffer.SetBufferData(passData.input, passData.bufferData);// Attach buffer to the compute shader// 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.commandBuffer.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.

Additional resources