How to change a specific material of an object at runtime ?

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.


I solved the problem (as suggested by another user in another question (the same as this) that i’ve opened for error):

Doing this way it works:

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

Thanks :slight_smile:

That should work fine. Perhaps it’s where you are calling it? Are you sure you aren’t overwriting it again later on?

try gameObject.renderer.materials[1] = theNewMaterial;