Updating multiple materials on one mesh only works after clicking in Inspector?

Sooo, I have an object with two materials on it. I create and store a reference to a new material, and can set the one color just fine by doing this pseudocode:

material1Copy = new Material(GetComponent<Renderer>().sharedMaterial)
material1Copy.color = whatever
GetComponent<Renderer>().material = material1Copy;

However, when trying to change material 1 AND 2 like

material1Copy = new Material(GetComponent<Renderer>().sharedMaterials[0]);
material2Copy = new Material(GetComponent<Renderer>().sharedMaterials[1]);

material1Copy.color = whateverColor1
material2Copy.color = whateverColor2

Material[] myMaterials = new Material[] { material1Copy, material2Copy };

GetComponent<Renderer>().sharedMaterials = myMaterials;

It doesn’t appear to work in the game view… but if I click on the object in the inspector while the game is playing, and click on the circles next to the materials, they update and magically display the right colors.

What am I missing?

This is in 5.1.1 using the standard shader.

Hi,

Does this only occur with the standard shader or all shaders? It sounds like you need to enable some keywords for the shader - Unity - Scripting API: Material.EnableKeyword
If it still does not work can you submit it as a bug so we can investigate?
Unity QA: Building quality with passion

Enabling keywords was the ticket, I needed to .EnableKeyword(ā€œ_EMISSIONā€) and everything magically started working.

Thanks Karl

1 Like

Thanks this helped a lot!

Note that if you are using the Standard Shader and trying to apply to ā€˜_BumpMap’, you have to use ā€˜_NORMALMAP’.

i am facing the same issue in Unity 5.6.1 and .EnableKeyword() is not helping…
I want to apply AOMap on the materials. AOMap and materials are in the asset bundle…
Please check my code -:
temp*.EnableKeyword(ā€œ_DETAIL_MULX2ā€);*
temp*.SetTexture(ā€œ_DetailAlbedoMapā€, aoTexture);
temp.SetFloat(ā€œ_UVSecā€, 1.0f);*