I'm using HDRP and I would like to extend it without actually modifying HDRP code or writting my own SRP.

I'd like to:

  1. Render some objects with a custom shader
  2. Have those objects increase a stencil value
  3. Setup the stencil state for the next camera in the list so that the main scene only renders again when the stencil matches that value

Here's my pseudo-code:

using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.Rendering;
using RenderPipeline = UnityEngine.Rendering.RenderPipelineManager;

public class MyRenderTest : MonoBehaviour
    private ushort m_StencilValue = 0; // The scene is only rendered if the stencil equals to this value

    void OnEnable()
        RenderPipeline.beginContextRendering += OnBeginContextRendering;
        RenderPipeline.beginCameraRendering += OnBeginCameraRendering;
        RenderPipeline.endCameraRendering += OnEndCameraRendering;

    void OnDisable()
        RenderPipeline.endCameraRendering -= OnEndCameraRendering;
        RenderPipeline.beginCameraRendering -= OnBeginCameraRendering;
        RenderPipeline.beginContextRendering -= OnBeginContextRendering;

    void OnBeginContextRendering(ScriptableRenderContext context, List<Camera> cameras)
        m_StencilValue = 0;

        // Unity clears the main stencil buffer before this call, so no need to do it ourselves

    void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
        SetStencilFunction(EQUAL, m_StencilValue); // Only render when the stencil equals m_StencilValue
        SetStencilOperation(KEEP); // Keep the value for the HDRP camera render

        // After this, HDRP would render the camera only where the stencil operation is verified

    void OnEndCameraRendering(ScriptableRenderContext context, Camera camera)
        DrawCustomObjects(); // Drawing the custom objects should increment the stencil value


I also thought of hooking up Custom Passes but the problem is the same, I can't find a way to actually set the Stencil Test Function and Stencil Operation.

Is this possible?

  • 1
    \$\begingroup\$ Stencil test functions and operations are set as part of the shader file, so you'll need to make modified versions of the built-in shaders for this. \$\endgroup\$
    – DMGregory
    Oct 21, 2022 at 18:55
  • 1
    \$\begingroup\$ @DMGregory Thank you, I'll try that and, if it works, I'll post a complete answer. \$\endgroup\$ Oct 21, 2022 at 19:36


You must log in to answer this question.

Browse other questions tagged .