概述
一句multi_compile后面写若干个关键字XXX,在代码里用#if XXX条件编译一段代码。关键字的开启关闭在材质debug界面。在Valid Keywords填的关键字如果在某句multi_compile里会自动进入Valid Keywords,否则进入Invalid。

哪里看变体数量

multi_compile A有几种变体
1种。A一定执行,不管有没有填A。
Shader "学变体_一个关键字"
{
Properties { }
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile A
struct appdata { float4 vertex : POSITION; };
struct v2f { float4 pos : SV_POSITION; };
v2f vert (appdata v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target {
fixed4 col;
#ifdef A
col=fixed4(1,0,0,1);
#endif
#if !defined(A)
col=fixed4(1,1,1,1);
#endif
return col;
}
ENDCG
}
}
}


multi_compile A会编译#if A的代码,就和#define A的效果是一样的。
multi_compile _ A有几种变体
2种,带A和不带的。
Shader "学变体_一个关键字和下划线"
{
Properties { }
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile A _
struct appdata { float4 vertex : POSITION; };
struct v2f { float4 pos : SV_POSITION; };
v2f vert (appdata v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target {
fixed4 col;
#ifdef A
col=fixed4(1,0,0,1);
#endif
#if !defined(A)
col=fixed4(1,1,1,1);
#endif
return col;
}
ENDCG
}
}
}




multi_compile A B C:允许从A B C选择一个关键字,都不开就执行第一个
如果没写任何关键字,则开启第一个关键字。
multi_compile A B _ C:允许从A B C选择一个关键字,或者不开
如果没写任何关键字,则不开。
总结
没有_,一句multi_compile就是多选一,必选一个,默认选第一个。
有_,就是多选1或0,默认不选。
做几个题吧
#pragma multi_compile A
#pragma multi_compile B C D
Shader "学变体"
{
Properties { }
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile A
#pragma multi_compile B C D
struct appdata { float4 vertex : POSITION; };
struct v2f { float4 pos : SV_POSITION; };
v2f vert (appdata v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target {
fixed4 col;
#ifdef B
col=fixed4(0,0,1,1);
#endif
#ifdef C
col=fixed4(0,1,0,1);
#endif
#ifdef D
col=fixed4(0,0,0,1);
#endif
#ifdef A
col=fixed4(1,0,0,1);
#endif
#if !defined(A) && !defined(B) && !defined(C) && !defined(D)
col=fixed4(1,1,1,1);
#endif
return col;
}
ENDCG
}
}
}
不开任何关键字:执行A,A必执行。3种。这里直接看

豆包说8个,deepseek说6个。

#pragma multi_compile A _
#pragma multi_compile B C D
Shader "学变体"
{
Properties { }
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile A _
#pragma multi_compile B C D
struct appdata { float4 vertex : POSITION; };
struct v2f { float4 pos : SV_POSITION; };
v2f vert (appdata v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target {
fixed4 col;
#ifdef B
col=fixed4(0,0,1,1);
#endif
#ifdef C
col=fixed4(0,1,0,1);
#endif
#ifdef D
col=fixed4(0,0,0,1);
#endif
#ifdef A
col=fixed4(1,0,0,1);
#endif
#if !defined(A) && !defined(B) && !defined(C) && !defined(D)
col=fixed4(1,1,1,1);
#endif
return col;
}
ENDCG
}
}
}








6种。