Version: Unity 6.0 (6000.0)
语言 : 中文
在 URP 中的渲染通道中运行计算着色器
在 URP 中分析渲染图

在 URP 中为计算着色器创建输入数据

在渲染通道中运行计算着色器时,可以分配缓冲区来为计算着色器提供输入数据。

请遵循以下步骤:

  1. 创建一个图形缓冲区,然后在通道数据中添加一个句柄。例如:

    // Declare an input buffer
    public GraphicsBuffer inputBuffer;
    
    // Add a handle to the input buffer in your pass data
    class PassData
    {
        ...
        public BufferHandle input;
    }
    
    // Create the buffer in the render pass constructor
    public 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));
    }
    
  2. 设置缓冲区中的数据。例如:

    var inputValues = new List<int> { 1, 2, 3, 4, 5 };
    inputBuffer.SetData(inputValues);
    
  3. 使用 ImportBuffer 渲染图 API 将缓冲区转换为渲染图系统可以使用的句柄,然后在通道数据中设置 BufferHandle 字段。例如:

    BufferHandle inputHandleRG = renderGraph.ImportBuffer(inputBuffer);
    passData.input = inputHandleRG;
    
  4. 使用 UseBuffer 方法可将缓冲区设置为渲染图形系统中的可读缓冲区。例如:

    builder.UseBuffer(passData.input, AccessFlags.Read);
    
  5. SetRenderFunc 方法中,使用 SetComputeBufferParam API 将缓冲区附加到计算着色器。例如:

    // 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 buffer
    context.cmd.SetComputeBufferParam(passData.computeShader, passData.computeShader.FindKernel("Main"), "inputData", passData.input);
    

示例

有关完整示例,请参阅通用渲染管线 (URP) 包示例中名为 Compute 的示例。

其他资源

在 URP 中的渲染通道中运行计算着色器
在 URP 中分析渲染图