Search Unity

Change sharedMaterials property has no effect

Discussion in 'General Graphics' started by zhutianlun810, May 14, 2021.

  1. zhutianlun810

    zhutianlun810

    Joined:
    Sep 17, 2017
    Posts:
    168
    Hello,

    I am stucked by a weird bug. I am trying to enable sharedMaterials' keyword. This is my code:
    Code (CSharp):
    1.             foreach (Material mat in mats)
    2.             {
    3.                 mat.EnableKeyword("_COMPRESSEDMESH");
    4.                 mat.SetFloat("_RenderBound", defaultRenderBound);
    5.                 UnityEditor.EditorUtility.SetDirty(mat);
    6.             }
    7.             AssetDatabase.SaveAssets();
    8.             AssetDatabase.Refresh();
    However, I find that although my svn shows the mat files have been changed successfully(by diff), the materials are not changed in UnityEditor(by enable debug view on inspector).
     
  2. zhutianlun810

    zhutianlun810

    Joined:
    Sep 17, 2017
    Posts:
    168
    I found the bug. The shaderGUI always override my settings...
     
  3. lclemens

    lclemens

    Joined:
    Feb 15, 2020
    Posts:
    761
    Can you explain that a little more? How and when does the GUI override the settings? Is there anything that can be done to prevent the settings from being overwritten?
     
  4. lclemens

    lclemens

    Joined:
    Feb 15, 2020
    Posts:
    761
    I found a solution!

    So before I was doing this...

    1) Material mat = new Material(shader)
    2) mat.CopyPropertiesFromMaterial(otherMaterial);
    3) mat.SetFloat("_MyParameter", 8.88f); // SetTexture(), etc
    4) AssetDatabase.CreateAsset(mat, path);
    5) AssetDatabase.SaveAssets();

    It seems like that would work just fine. But no!!
    I had to change it to:

    1) Material mat = new Material(shader)
    2) AssetDatabase.CreateAsset(mat, path);
    3) mat.CopyPropertiesFromMaterial(otherMaterial);
    4) EditorUtility.SetDirty(mat);
    5) AssetDatabase.SaveAssets(); // middle save
    6) mat.SetFloat("_MyParameter", 8.88f); // SetTexture(), etc
    7) EditorUtility.SetDirty(mat);
    8) AssetDatabase.SaveAssets(); // final save

    Success!

    One big change was moving CreateAsset() to the beginning so that I could call save earlier.

    The other was setting dirty and saving after CopyPropertiesFromMaterial() but before calling SetFloat(). Without that, all changes go bye-bye. Something funky is going on inside CopyPropertiesFromMaterial().