Legacy Documentation: Version 4.6.2
Language: English
Built-in state variables in shader programs
GLSL Shader Programs

Making multiple shader program variants

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Sumbission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Often it is convenient to keep most of a piece of shader code fixed but also allow slightly different shader “variants” to be produced. This is commonly called “mega shaders” or “uber shaders”, and is achieved by compiling the shader code multiple times with different preprocessor directives for each case.

In Unity this can be achieved by adding a #pragma multi_compile directive to a shader snippet. 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).

How multi_compile works

A directive like:

    #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.

There can be more than two keywords on a multi_compile line, for example this will produce four shader variants:

    #pragma multi_compile SIMPLE_SHADING BETTER_SHADING GOOD_SHADING BEST_SHADING

Combining several multi_compile lines

Several multi_compile lines can be provided, and the resulting shader will be compiled for all possible combinations of the lines:

    #pragma multi_compile A B C
    #pragma multi_compile D E

This would produce three variants for first line, and two for the second line, or in total six shader variants (A+D, B+D, C+D, A+E, B+E, C+E).

It’s easiest to think of each multi_compile line as controlling a single shader “feature”. Keep in mind that the total number of shader variants grows really fast this way. For example, ten multi_compile “features” with two options each produces 1024 shader variants in total!

Keyword limit

When using shader variants, you should bear in mind that there is a limit of 64 keywords in Unity and a few of these are used internally and therefore subtract from the limit. Also, the keywords are enabled globally throughout a particular Unity project so you should be careful not to exceed the limit when multiple keywords are defined in several different shaders.

Built-in state variables in shader programs
GLSL Shader Programs