- Home /
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.
Thanks!
Answer by ops8086 · Oct 27, 2011 at 06:00 PM
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 :)
Answer by BalsamicVinegar · Oct 27, 2011 at 12:45 AM
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;
You'd think that should work (and nothing in the documentation suggests it wouldn't) but it doesn't work. I think the elements of the array must be read-only, but the array itself isn't which is why @ops8086's solution is correct. I just ran into this problem and changing the whole array was the only way to get it to work
I think you're right on that. I was driving myself crazy on this using the gameObject.getComponent().materials[1] = theNew$$anonymous$$aterial; and like you said it definitely must be read only because your solution is the only thing that works, $$anonymous$$aybe its a bug or a missing point in the documentation but as of Unity 2017 this is still the way it has to be done.
Your answer
Follow this Question
Related Questions
Material doesn't have a color property '_Color' 4 Answers
How to change a specific material of an object ? 0 Answers
Changing two different objects renderer colour 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Can I access the Material of an animated object via code? 1 Answer