Making multiple shader program variants

Often it's convenient to write shader code mostly once, but produce slightly different shader "variants" for it. 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, appropriate shader variant is picked up from 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, based on Material or global shader keywords, one of them will be picked up. 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 BESTEST_EVER_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, e.g. ten multi_compile "features" with two options each produces 1024 shader variants in total!

Page last updated: 2013-10-07