Version: 2019.3
LanguageEnglish
  • C#

RenderTextureSubElement.Stencil

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Description

Stencil element of a render texture.

Used to access the stencil data of the underlying surface from a render texture and bind it in a shader. Make sure you set the stencilFormat of your render texture to a format supported on the target platform before it is created.

To access the stencil information in a shader, you need to read it from the correct channel. The stencil data is stored in the red channel for all graphics APIs that support it except for DirectX 11, in which case it is stored in the green channel.

If the stencilFormat is set to R8_UInt, you need to use the function Load to read from the texture. Otherwise, if the format is R8_UNorm you can use sampling.

When using MSAA render textures, you need to define the stencil texture using the equivalent MS texture types.

You cannot bind the stencil buffer as a RWTexture.

Below is an example Unlit shader that reads the stencil information from a render texture with stencilFormat R8_UInt and writes it as color information on the green channel.

See Also: GraphicsFormat.

Shader "Unlit/ExampleShader"
{
    Properties
    {
        _ExampleTex("Texture", 2D) = "" {}
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" }
        LOD 100

Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma target 4.0

#include "UnityCG.cginc"

struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; };

struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; };

#if SHADER_API_D3D11 #define STENCIL_CHANNEL g #else #define STENCIL_CHANNEL r #endif

Texture2D<uint2> _ExampleTex;

v2f vert(appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.uv; return o; }

fixed4 frag(v2f i) : SV_Target { int xRes = 1024; int yRes = 768;

uint stencil = _ExampleTex.Load(int3(floor(i.uv.x * xRes), floor(i.uv.y * yRes), 0)).STENCIL_CHANNEL; fixed4 col = float4(0.0, float(stencil) / 255.0f, 0.0, 1.0);

return col; }

ENDCG } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961