How to change a specific material of an object ?

Hi saw that this question has posted many times, but all the times the answer is to use renderer.material = theNewMaterial;

The problem is that if the current object has more than one material in the Renderer, how can i change a specific material ? For example, i have an object whose mesh is composed by 4 materials, so in the renderer i have material[0], material[1], and so on. What i’ve to do if i want to assign (at runtime) another material to the material at index 1, for example ?

Doing this way doesn’t work:

renderer.materials[1] = theNewMaterial;

I hope someone can help me.

Thanks!

According to the docs, Renderer.materials is just a copy of the internal array - that’s why modifying one of its elements doesn’t work. You should copy the materials to a temp array, modify the element and store the temp array in materials:

    var mats = renderer.materials;
    mats[1] = theNewMaterial;
    renderer.materials = mats;