Skip to content

Instantly share code, notes, and snippets.

Last active January 27, 2021 06:32
Show Gist options
  • Save aras-p/b2a0952161cb0c2b2cc0 to your computer and use it in GitHub Desktop.
Save aras-p/b2a0952161cb0c2b2cc0 to your computer and use it in GitHub Desktop.
Controlling fixed function states from materials/scripts in Unity

(typing off the top of my head, might not compile)

Since Unity 4.3:

In the shader, instead of writing Cull Off, write Cull [_MyCullVariable], the value will be fetched from the material or global float/int variable _MyCullVariable then.

You could have it be part of material, e.g. inside Properties block:

[Enum(Off,0,Front,1,Back,2)] _MyCullVariable ("Cull", Int) = 1

That Enum thing in front will make it be a combobox in the UI. Values match with UnityEngine.Rendering.CullMode enum.

And then from a script, you can do:

material.SetInt ("_MyCullVariable", (int)UnityEngine.Rendering.CullMode.Back)

Look at other enums in UnityEngine.Rendering namespace for various values (for Blend modes, Stencil, ZTest etc.)

However, you can not control these variables from a MaterialPropertyBlock values; they really have to be set on the material itself or as global shader properties.

Note that using this thing (controlling gfx states via material properties) is a tiny bit more expensive than regular, particularly:

  • When changing the value on the material, some of underlying graphics states (e.g. DX11 states) have to be rebuilt. This is a cost that happens on change.
  • When you have stuff driven by global shader properties, then it's marginally more costly to apply the material too, since it basically has to check "did anything from globals change that might need rebuild of my states?"

I should stop being lazy and write some decent documentation of all this

Copy link

in the words of Ron Swanson, please and thankyou

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment