- Home /
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!
Are you sure it doesn't work? The new material is a new material instance, or a material reference from a prefab? Check out the inspector for the object to be sure.
Answer by aldonaletto · Oct 27, 2011 at 11:59 AM
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;
Just in case anyone stumbles across this whilst looking for C# instructions like I did, this worked for me:
$$anonymous$$aterial[] mats;
mats = renderer.materials;
mats[1] = theNew$$anonymous$$aterial
renderer.materials = mats;
hi, noob coder, does this go under void update? Confused as how to finish the code off as it seems to only be a part of it. Thanks
In C#...
$$anonymous$$aterial[] mats;
This ^ goes below "public class yourScript : $$anonymous$$onoBehaviour {" and before void Update or any other functions.
mats = renderer.materials;
mats[1] = theNew$$anonymous$$aterial
renderer.materials = mats;
These ^ go where ever you want to make the material to change.
Hope that makes sense.
Not sure about Javascript if that's what you were after.
@Slandapanda the OP is using valid c#, nothing needs to be changed. caching it in the class doesnt really change anything either, still returns a new copy and GC cleans up the dereferenced array.