Description of Requirement
Check the button in the Inspector panel to act as a switch. If the button is checked, the sample map is used; if the button is not checked, the normal color is used.
Code
Shader "MyShader/ShaderToggle"
{
Properties
{
[MaterialToggle(_TEX_ON)] _Toggle("Enable Main texture", Float) = 0 //1
_MainTex ("Texture", 2D) = "white" {
}
}
SubShader
{
Tags {
"RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile _TEX_OFF _TEX_ON
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
#if _TEX_ON
float2 uv : TEXCOORD0;
#endif
};
#if _TEX_ON
sampler2D _MainTex;
half4 _MainTex_ST;
#endif
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
#if _TEX_ON
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
#endif
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = fixed4(1,1,0,1);
#if _TEX_ON
col = tex2D(_MainTex, i.uv);
#endif
return col;
}
ENDCG
}
}
}
be careful
-
#pragma multi_compile _TEX_OFF _TEX_ON
Two shader versions are compiled here, one is _TEX_OFF and the other is _TEX_ON.
_TEX_OFF does not appear in the shader code throughout, and can be understood as a shader at the bottom.
And _TEX_ON is the shader code after the switch is turned on. -
Also note that the code blocks of #if ... #endif use, for example:
only when the switch _TEX_ON is turned on do we define texture coordinates and texture map reference variables:
#if _TEX_ON
float2 uv : TEXCOORD0;
#endif
#if _TEX_ON
sampler2D _MainTex;
half4 _MainTex_ST;
#endif
_TEX_ON result checked
Uncheck _TEX_ON result