Certainly! Here's how you can write a simple Unity HLSL shader (or ShaderLab shader) that samples _MainTex or _MaskTex based on _Val < 0.5f.
✅ Goal:
- Use
_Val (a float property) to choose whether to sample from _MainTex or _MaskTex.
- If
_Val < 0.5, sample _MainTex; otherwise, sample _MaskTex.
🧱 Shader Properties:
Shader "Custom/ConditionalTextureShader"
{
Properties
{
_MainTex ("Main Texture", 2D) = "white" {}
_MaskTex ("Mask Texture", 2D) = "black" {}
_Val ("Control Value", Float) = 0.0
}
🧾 Full Shader Example:
Shader "Custom/ConditionalTextureShader"
{
Properties
{
_MainTex ("Main Texture", 2D) = "white" {}
_MaskTex ("Mask Texture", 2D) = "black" {}
_Val ("Control Value", Float) = 0.0
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
sampler2D _MainTex;
sampler2D _MaskTex;
float _Val;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 color;
if (_Val < 0.5f)
color = tex2D(_MainTex, i.uv);
else
color = tex2D(_MaskTex, i.uv);
return color;
}
ENDCG
}
}
}
✅ Notes:
- _MainTex: Base texture.
- _MaskTex: Alternative texture used conditionally.
- _Val: Threshold controller. If it's less than
0.5, we use _MainTex. Otherwise, _MaskTex.
➕ Optional Optimized Version (No Branching):
To avoid if statements and reduce shader branching/performance cost, you can lerp between the two values:
fixed4 colorMain = tex2D(_MainTex, i.uv);
fixed4 colorMask = tex2D(_MaskTex, i.uv);
fixed t = step(0.5f, _Val); // 0 if _Val < 0.5, 1 otherwise
fixed4 color = lerp(colorMain, colorMask, t);
Replace the frag function's body with that if you prefer performance over branching precision.
Let me know if you're using URP or HDRP, and I can provide a Shader Graph or SRP-compatible version as well!