Renderer Materials not changing elements

Hello,

I have a simple script that changes the elements of a object. What is wrong this the following?

children.GetComponent<Renderer>().materials[0] = mat;
children.GetComponent<Renderer>().materials[1] = mat2;

The above doesn’t change any mats nor does it throw an error. The blow does indeed work.

children.GetComponent<Renderer>().material = mat;

I’ve looked around the internet on a fix but I couldn’t find anything that works.

Thanks.

Renderer.materials returns a copy, so you’re not working on the actual array here (see note on this page: Unity - Scripting API: Renderer.materials ).

You need to do something like this…

Renderer r= children.GetComponent<Renderer>();
Material[] mats = r.materials;
mats[0] = mat;
mats[1] = mat2;
r.materials = mats; // this is the key - you need to set the renderers materials array to the one you've modified