How can I change the shader parameters for an UI Image?

How can I change the shader parameters for an UI Image?

So, inside a canvas I have an image. I have written a custom shader for it and I want to set a shader parameter using SetFloat().

I’m trying this:

myImage.materail.SetFloat( “Param”, 1f );

But the setting the parameter will access the global material, thus affecting all images. I want to access the instance material for the image so that I change only that single image. How can I do this?

Footnote: I do know how to do this for meshes. There I access the material for the renderer component and it works. But for UI Images this there is no render compenent.

I just ran into the same problem. I solved it like this:

Material mat = Instantiate(image.material);
mat.SetFloat("_SomeProperty", 1f);
image.material = mat;

As of 2020 onwards, I think the better solution for play mode is to use image.materialForRendering.

myImage.materialForRendering.SetFloat("Param", 1f);

This works for me, and it avoids the memory overhead of creating a new Material each frame/editor update.

Source: https://forum.unity.com/threads/trying-to-animate-an-image-component-material-shader.265023/#post-7220341

(For edit mode, you’ll still have to use Matkins’s solution).

The following is true for all renderers I have worked with, I’m assuming it is true for UI.Image components as well (Unity GUI images): Just use the renderer.material of the object. Renderer.sharedMaterial is the global one, but as soon as you access the renderer.material Unity makes the material it’s own instance.