arti
arti

Reputation: 657

How to change materials in Unity

I have stuck a bit on a material change in my Unity project. I have an object with 8 materials on it, I want to change material number 5 when button pressed. Following code doesn't work:

objectToPaint.GetComponent<Renderer>().materials[4] = availableMaterials[i];

when I do:

objectToPaint.GetComponent<Renderer>().material = availableMaterials[i];

it will change only 1st material and also proves, triggers are working perfectly. Any suggestions?

Upvotes: 2

Views: 15938

Answers (2)

Valentin
Valentin

Reputation: 5488

You have to change renderer.materials, instead of changing renderer.material

As I consider, this should work

Material[] mats = renderer.materials; 
mats[4] = availableMaterials[i]; 
renderer.materials = mats;

Upvotes: 8

arti
arti

Reputation: 657

So after a lot of tries and errors, found that you can't change just 1 material in array. I had to assign entire array to temporary array, change desired material and then assign temporary array to the object.

Upvotes: 8

Related Questions