Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Resolved Material.EnableKeyword is not work in build when the Material is created at runtime

Discussion in 'Shaders' started by reeenyson, May 10, 2023.

  1. reeenyson

    reeenyson

    Joined:
    Jun 14, 2022
    Posts:
    4
    Hi
    I packed my shader and ShaderVariants file in one assetbundle and build.

    If the material is created in the editor and assigned to an object, there should be no issue with displaying the shader effect properly.
    Code (CSharp):
    1. m_SpriteRenderer.sharedMaterial.EnableKeyword("HITEFFECT_ON");
    If the material is dynamically created at runtime and then assigned to an object, the shader effect may not work properly.
    Code (CSharp):
    1.  Material mat = new Material(Shader.Find("AllIn1SpriteShader/AllIn1SpriteShader"));
    2. m_SpriteRenderer.sharedMaterial = mat;
    3. m_SpriteRenderer.sharedMaterial.EnableKeyword("HITEFFECT_ON");
    Could you please help to check the question, Thanks!
     
  2. aleksandrk

    aleksandrk

    Unity Technologies

    Joined:
    Jul 3, 2017
    Posts:
    2,864
    Hi!
    If you intend to switch keywords on materials at runtime, they should be declared using
    #pragma multi_compile
    instead of
    #pragma shader_feature
    . The latter determines the variants automatically based on existing materials that go into the build. If you create one using a script, the variant may not be present.
     
  3. reeenyson

    reeenyson

    Joined:
    Jun 14, 2022
    Posts:
    4
    Thank you for help! I got it!
     
  4. XYHC

    XYHC

    Joined:
    Jan 4, 2019
    Posts:
    6
    I recently got AllIn1SpriteShader and have been having a similar issue where some material properties (namely "_GrassManualToggle" and "_GrassManualAnim") modified at runtime aren't updating until I expanded the properties in the inspector - I've tried enabling those keywords in code, but it does not fix the issue.

    The issue's different from yours as I'm not creating the material during runtime, but I've searched all over without finding a fix :( So you're my only hope haha.
    Have you run into similar issues?