How Unity compiles branching shaders
Choose dynamic branching or shader variants.
読み終わるまでの所要時間 3 分最終更新 1ヶ月前
When you use a keyword, you can choose how Unity compiles the shader code. The options are:
- Dynamic branching: Unity keeps branching code in one compiled shader program.
- Shader variants: Unity compiles a separate shader program called a shader variant for each branch. This is a form of static branching, and can help minimize your shader code.
Dynamic branching
To use dynamic branching, use to declare keywords. For example:
#pragma dynamic_branch#pragma dynamic_branch RED GREEN...if (RED){ // Output red}else if (GREEN){ // Output green}
At compile time, Unity converts each keyword into a uniform integer variable in the compiled shader code, which can have a value of either or . At runtime, for each draw call, Unity sends the state of each keyword integer to the GPU.
01You can use if your shaders run on a fast GPU, and don't have asymmetric code branches where one branch is longer or more complex than the other.
dynamic_branchShader variants
To use shader variants, use or to declare keywords. For example:
#pragma multi_compile#pragma shader_feature#pragma multi_compile RED GREENif (RED){ // Output red}else if (GREEN){ // Output green}
At compile time, Unity splits the previous code into 2 separate but similar shader files called shader variants. One file contains the code that outputs red, and the other contains the code that outputs green. Each draw call, Unity sends the GPU the correct shader variant.
During compilation of each shader variant, Unity does the following:
- Sets an enabled keyword as in a preprocessor macro. For example
1becomesRED, so#define RED 1becomesif (RED).if (1) - Sets a disabled keyword as in a uniform integer variable. For example
0becomesGREEN, sostatic const int GREEN = 0;becomesif (GREEN)and the compiler removes the branch.if (0)
Choosing a shader variant type
If you only need a shader to branch based on material properties, use . Unity compiles shader variants for keyword combinations that materials in your build use, and removes other shader variants. This keeps build times low and file sizes small.
shader_featureIf you need to use a C# script to make the shader branch at runtime, use . Unity compiles shader variants regardless of whether they're used by materials in your build. For example, you can use to give users dynamic control over whether fog appears in a game.
multi_compilemulti_compile