參考鏈接:
https://blog.csdn.net/qq826364410/article/details/81774741
https://docs.unity3d.com/Manual/SL-MultipleProgramVariants.html
1.#pragma multi_compile MY_multi_1 MY_multi_2
定義了兩個shader關鍵字,一個是MY_multi_1,另一個是MY_multi_2
MultiCompile.shader
1 Shader "Custom/MultiCompile" 2 { 3 SubShader 4 { 5 Pass 6 { 7 CGPROGRAM 8 #pragma vertex vert 9 #pragma fragment frag 10 #pragma multi_compile MY_multi_1 MY_multi_2 11 12 #include "UnityCG.cginc" 13 14 struct appdata 15 { 16 float4 vertex : POSITION; 17 }; 18 19 struct v2f 20 { 21 float4 vertex : SV_POSITION; 22 }; 23 24 v2f vert (appdata v) 25 { 26 v2f o; 27 o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); 28 return o; 29 } 30 31 fixed4 frag (v2f i) : SV_Target 32 { 33 fixed4 col = fixed4(1, 0, 0, 0); 34 #ifdef MY_multi_1 35 col = fixed4(0, 1, 0, 0); 36 #endif 37 #ifdef MY_multi_2 38 col = fixed4(0, 0, 1, 0); 39 #endif 40 return col; 41 } 42 ENDCG 43 } 44 } 45 }
測試如下,來回按下QW,即可以看到兩種顏色的切換
1 using UnityEngine; 2 3 public class MultiCompile : MonoBehaviour { 4 5 void Update () 6 { 7 if (Input.GetKeyDown(KeyCode.Q)) 8 { 9 Shader.EnableKeyword("MY_multi_1"); 10 Shader.DisableKeyword("MY_multi_2"); 11 } 12 else if(Input.GetKeyDown(KeyCode.W)) 13 { 14 Shader.EnableKeyword("MY_multi_2"); 15 Shader.DisableKeyword("MY_multi_1"); 16 } 17 } 18 }
2.#pragma multi_compile __ MY_multi_3
定義了一個shader關鍵字,MY_multi_3
MultiCompile2.shader
1 Shader "Custom/MultiCompile2" 2 { 3 SubShader 4 { 5 Pass 6 { 7 CGPROGRAM 8 #pragma vertex vert 9 #pragma fragment frag 10 #pragma multi_compile __ MY_multi_3 11 12 #include "UnityCG.cginc" 13 14 struct appdata 15 { 16 float4 vertex : POSITION; 17 }; 18 19 struct v2f 20 { 21 float4 vertex : SV_POSITION; 22 }; 23 24 v2f vert (appdata v) 25 { 26 v2f o; 27 o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); 28 return o; 29 } 30 31 fixed4 frag (v2f i) : SV_Target 32 { 33 fixed4 col = fixed4(1, 0, 0, 0); 34 #ifdef MY_multi_3 35 col = fixed4(1, 1, 1, 0); 36 #endif 37 return col; 38 } 39 ENDCG 40 } 41 } 42 }
測試如下,來回按下ER,即可以看到兩種顏色的切換
1 using UnityEngine; 2 3 public class MultiCompile2 : MonoBehaviour { 4 5 void Update () 6 { 7 if (Input.GetKeyDown(KeyCode.E)) 8 { 9 Shader.EnableKeyword("MY_multi_3"); 10 } 11 else if (Input.GetKeyDown(KeyCode.R)) 12 { 13 Shader.DisableKeyword("MY_multi_3"); 14 } 15 } 16 }