Create a gist now

Instantly share code, notes, and snippets.

@aras-p /foo.md
Last active Nov 23, 2017

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

TJHeuvel commented Jul 4, 2017

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

Yes please!

smkplus commented Jul 25, 2017

Bravo cool stuff
ایول جالبه حال کردم
I make full controlling here :D
https://gist.github.com/smkplus/2a5899bf415e2b6bf6a59726bb1ae2ec

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