How do I change the material of an object with Script in Unity?

How do I change the material of an object with Script in Unity?

I was making a game with Unity and I want to change an object's material using UnityScript when the player collects 5 collectables that I made. The collectables get stored in an int variable called Score.

Solutions/Answers:

Answer 1:

If you want to change a Material in Unity you have to retrieve it first.

If your GameObject uses a Material it means that it uses a Renderer.

You can retrieve your object renderer using the internal variable renderer or get it using the GetComponent function. On the renderer object you will find a material property containing the active Material.

For example:

MeshRenderer my_renderer = GetComponent<MeshRenderer>();
if ( my_renderer != null )
{
   Material my_material = my_renderer.material;
}

If you want to change the current material, you can use the same access. For example:

my_renderer.material = other_material;

I suggest to make other_material a public Material variable of your game object. However if you want to load it at runtime you should have a look at Resources.Load.

I hope it helps.

Answer 2:

public Material[] mainMat;

Renderer rend;

public static int index;

public static int i;

public void Start()
{
    rend = GetComponent<Renderer> ();
    rend.enabled = true;
//  rend.sharedMaterial = mainMat [0];
}

public void changeMat()
{
    if (i == 0) {
        rend.sharedMaterial = mainMat [0];
        i++;
    } 
    else if (i == 1) 
    {
        rend.sharedMaterial = mainMat [1];
        i++;
    }

References