Skip to main content

Optimize and Lock

Each material on this shader has an option to 'Optimize & Lock'. By clicking on this button, the material will undergo an optimization process and produce a 'optimized & locked' shader that is fast and ready to be used in game and then assign this new shader to the material.

We do this for a few reasons but ultimately it's to increase FPS in game.

Optimize and lock button


Optimization Steps

Property baking

Taking property values that aren't animated and directly writing them into the shader. The result of this is that the shader compiler can do 'constant folding' - now that the compiler knows what values certain properties have, it can precompute math computations, branch results so that they don't have to be done every frame in game.

More information on property animation and renaming can be found here

Interpolator removal

Interpolators carry information from one stage of the shader to another. The optimizer can tell which interpolators will not end up being used and remove them, so the GPU doesn't do unnecessary work.

Unused Texture Removal

Texture samples aren't the cheapest things in GPUs and sometimes we have materials that sample default textures. So, why sample the default texture when we can just tell the optimized shader that there is no texture to sample and it should just use a known default value? So we do that.

Local Keyword Baking

Certain Unity versions have a limited amount of local keywords. They let us toggle expensive features of the shader on/off (this is why sometimes the shader recompiles when you turn a feature on/off - we're toggling a local keyword). So because of this limit, we bake the on/off switches into the shader itself.


Locking Steps

Handling of animated and renamed properties

Animated properties will not be baked into the shader. For renamed properties, we need to generate a 'clone' property that has the rename suffix on it so that we can properly target it with our animation clips.

Stencil modes

A shader can only have the 'basic' stencil mode or the 'front/back' mode. Instead of having 2 shaders that have different modes, we just adjust the stencil mode during the locking process as we're already editing the shader code during it.

More information about stencils can be found here

Material variant flattening

The material editor tooling in this shader does not support material variants, so we have to flatten them to normal materials during the locking step.