Change Material of an Object.

Hi,

How can I change a material of an object in Unity when I press a key? I know how I do something while pressing a key, but can't find how to change materials.

For example: I have a weapon and it has different abilities. Each abilitie has a color and the gun has to change textures. I want to change material(not only textures) because material sets textures and opacity of an object.

I'm using javascript to do this.

Thanks in advance.

What i do i maintain a list of materials in the object and change the material by simply settings renderer.material to the one is the list.

for eg: this is my set material function

void SetMat(int nIdx)
{
    renderer.material = m_aMaterials[nIdx];
}

Not sure if this approach is the best though

Hi,

Yes for some reason changing the individual materials in the array doesn't work. not sure why that is...

However changing the complete arrary does work.

So if you have an array of materials called: alternateMaterials; The following will not work:

body.renderer.material[0] = alternateMaterials[0];

However this will work:

body.renderer.materials = alternateMaterials;

At least for me!

If you want to change just one of hte materials at run time then you'll need to copy the list of materials out of the render object into a new array, change the material you want to change then reassign the renderer material array to the new one as above. Make sense?

regards,

Tony Oakden

Hey guys - the reason why Unity will NOT allow you to switch the materials is because Unity is passing you a copy of the array and so you need to set the array in order to apply the changes.

The following sentence is taken from the Unity docs:

Note that like all arrays returned by Unity, this returns a copy of materials array. If you want to change some materials in it, get the value, change an entry and set materials back.

Here is the link:

[Unity - Scripting API: Renderer.materials][1]

Were you able to do anything with renderer.materials*

* *

I'm having the same issue (I can do it one at a time) but I can't seem to loop over the Materials Array and make any changes.

* *

example: renderer.material=shieldMaterial; //Works every time

* _

renderer.materials *= shieldMaterial; //Doesn't work

*_

var material1 : Material;
var material2 : Material;

function OnChangeMaterial()
{
   // toggle between the two materials
   if( renderer.material == material1 )
     renderer.material = material2;
  else
     renderer.material = material1;

}