Updating custom material properties for RawImage

I’m having some difficulty updating custom material properties for a RawImage UI element. I’ve written a custom shader (which works perfectly) that I’ve assigned to a “CustomMaterial” material and then added to the Material property for the RawImage at runtime. In code I’m then setting some of the material properties when the element is instantiated (such as color, gradient level, etc. that work with my shader). First time up everything works fine. But if I try to update the material properties, nothing gets sent through following a SetActive(false) and then subsequent SetActive(true).

Here’s what I’m doing (objImage is a RawImage) –

        // Instantiate material so it's not shared
        objImage.texture = myTexture;
        objImage.material = Instantiate(Resources.Load("myCustomMaterial")) as Material;

        // Push colors through to material
        objImage.material.SetColor("_Color1",Color.red);
        objImage.material.SetColor("_Color2",Color.blue);

Everything is great, works just fine. So… I want to hide the UI and bring it back later with different properties (change the texture, update the shader parameters, etc.). In the meantime the object has been set to inactive objImage.gameObject.SetActive(false). After the object is set to active, everything seems to get BLOWN AWAY, all material properties are gone. The shader is relying on it’s own default values. It looks like there may be an issue with RawImage objects that are deactivated and then reactivated losing their material properties.

It doesn’t matter if I try to set any of the material properties, they are completely ignored.

Can anybody verify if this is a bug or if I’m not using the material property for RawImage correctly. I remember in NGUI they would handle this using the onRender callback to assign custom material properties.

– Brian.

Found the solution!

To remove the shared material you will need to instante the material(create a new one) and then set back to the image:

Material mat = Instantiate(image.material);
image.material = mat;

A few months late but maybe this might help someone else. I’ve found that by enabling the keywords on the shaders in custom unity shaders, it sort of ‘instantiates’ them to work properly. Call it in the awake or start functions on your Material object, maybe it will help.