【multi_compile】
Used to compile the shader code multiple times with different preprocessor directives for each case.
#pragma multi_compile
#pragma shader_feature
At runtime, the appropriate shader variant is picked up from the Material keywords (Material.EnableKeyword and DisableKeyword) or global shader keywords (Shader.EnableKeyword and DisableKeyword).
1、How multi_compile works
#pragma multi_compile FANCY_STUFF_OFF FANCY_STUFF_ON
Will produce two shader variants, one with FANCY_STUFF_OFF
defined, and another with FANCY_STUFF_ON
. At runtime, one of them will be activated based on the Material or global shader keywords.
If neither of these two keywords are enabled then the first one (“off”) will be used.
Following will produce four shader variants:
#pragma multi_compile SIMPLE_SHADING BETTER_SHADING GOOD_SHADING BEST_SHADING
When any of the names are all underscores, then a shader variant will be produced, with no preprocessor macro defined.
Following directive below will produce two shader variants; first one with nothing defined, and second one with FOO_ON
defined:
2、Difference between shader_feature and multi_compile
The only difference is that unused variants of shader_feature shaders will not be included into game build. So shader_feature makes most sense for keywords that will be set on the materials, while multi_compile for keywords that will be set from code globally.
Additionally, it has a shorthand notation with just one keyword,Which is just a shortcut for #pragma shader_feature _ FANCY_STUFF
, i.e. it expands into two shader variants (first one without the define; second one with it).
#pragma shader_feature FANCY_STUFF
#pragma shader_feature _ FANCY_STUFF
3、Keyword limit
There is a limit of 256 keywords in Unity, and around 60 of them are used internally.
So be careful not to exceed the limit when multiple keywords are defined in several different Shaders.
4、Built-in multi_compile shortcuts
以下是一些“shortcut”,即意味着一个命令对应着多个 multi_compile。
multi_compile_fwdbase
compiles all variants needed byForwardBase
(forward rendering base) pass type. The variants deal with different lightmap types and main directional light having shadows on or off.multi_compile_fwdadd
compiles variants forForwardAdd
(forward rendering additive) pass type. This compiles variants to handle directional, spot or point light types, and their variants with cookie textures.multi_compile_fwdadd_fullshadows
- same as above, but also includes ability for the lights to have realtime shadows.multi_compile_fog
expands to several variants to handle different fog types (off/linear/exp/exp2).
为了减少一些内置条件选项,可以用skip_variants:
#pragma multi_compile_fwdadd // will make all variants containing // "POINT" or "POINT_COOKIE" be skipped #pragma skip_variants POINT POINT_COOKIE
参考:https://docs.unity3d.com/Manual/SL-MultipleProgramVariants.html