Skip to content

Instantly share code, notes, and snippets.

Last active January 27, 2021 06:32
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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

TJHeuvel commented Jul 4, 2017

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

Yes please!

Copy link

smkplus commented Jul 25, 2017

Bravo cool stuff
I make full controlling here :D

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