- Home /
 
 
               Question by 
               Xenerade · Aug 24, 2020 at 06:43 PM · 
                uirenderingmaterialperformance optimizationstencil  
              
 
              StencilMaterial class
A couple of days ago I stumbled upon the StencilMaterial class located in the UnityEngine.UI namespace. According to its own description, it is a "Dynamic material class that makes it possible to create custom materials on the fly on a per-Graphic basis, and still have them get cleaned up correctly". This sounded promising so I started searcing the web about how to use it, but to my surprise I couldn't find anything about it anywhere. I tried this code, but it instantly closed unity everytime i tried running it.
 public Material instancedMaterial;
 public int ID;
 public bool initialized;
 
 [ExecuteInEditMode]
     protected override void OnEnable()
     {
         if (!initialized)
         {
             ID = Mathf.Abs(Guid.NewGuid().GetHashCode());
             Material advancedMaterial = (Material)AssetDatabase.LoadAssetAtPath("Assets/Materials/AdvancedSprite.mat", typeof(Material));
             instancedMaterial = new Material(advancedMaterial);
             instancedMaterial.SetColor("_TestColor", color);
             StencilMaterial.Remove(instancedMaterial);
 
             //Material of the Graphic compoonent
             material = StencilMaterial.Add(instancedMaterial, ID, UnityEngine.Rendering.StencilOp.Keep, UnityEngine.Rendering.CompareFunction.Disabled, UnityEngine.Rendering.ColorWriteMask.All, 255, 255);
 initialized = true;
         }
     }
 
               Any tips on where to start? I am using this for my UI to send unique data to elements with the same material, since MaterialPropertyBlock did not work on UI based meshes.
               Comment
              
 
               
              Your answer