Search Unity

MaterialPropertyBlock + shader keywords

Discussion in 'General Graphics' started by any_user, Jul 15, 2016.

  1. any_user

    any_user

    Joined:
    Oct 19, 2008
    Posts:
    374
    Is there any way to enable/disable shader keywords when rendering with Graphics.DrawMesh? I don't see anything in MaterialPropertyBlock, is there another way to do it?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Shader keywords are used by the shader compiler to internally generate multiple different shaders. You can think of doing Material.EnableKeyword() as being the same thing as Material.SetShader() at least as far as the GPU is concerned. Material property blocks can only set values that are passed to a shader, not change the shader itself.
     
    AlejMC likes this.
  3. any_user

    any_user

    Joined:
    Oct 19, 2008
    Posts:
    374
    I'm aware that EnableKeyword selects a shader variant, maybe I should rephrase my question: I'm looking for a way to render different meshes with different variants of a shader, without creating copies of the material for all the combinations (3x3x2=18 versions). Is there a way to do that?
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    No, different shaders or shader variants require the use of different materials.

    You can let Unity generate a new material instance per renderer at runtime with renderer.material.EnableKeyword(), or pre-allocate them, or a handful of similar method. Ultimately you will end up with multiple materials.

    Depending on what you're doing it might be worthwhile to not use shader variants and just use if statements in the shader if you want to reduce the number of variants. But if you're trying to avoid multiple materials for reasons of draw call reduction unless you are using Unity 5.4 and your shaders are setup for instancing those material property blocks are still going to add draw calls.