Changing a material at runtime on a MeshRenderer

I thought I could change a material at runtime on a MeshRenderer. I have a mesh with two materials on it, I get a reference to the meshrenderer and change the material I want:

Essentially I want when a collision happens with player and a tile the tile to blink.

So I have a script blinktile.

MeshRenderer myRend;
Material myBlinkMaterial;

void Start () {
   myRend = gameObject.GetComponent<MeshRenderer> ();
}

//called once we know we collided.
IEnumerator CollideFlash()
{
             myRend.materials[1] = blinkMaterial;
             myRend.materials[1].color = Color.white;
             Debug.Log("Name: " + myRend.materials[1].name); //prints out original name not what it is set to in blinkMaterial
             yield return new WaitForSeconds(0.1f);
             myRend.materials[1] = m;
             myRend.materials[1].color = c;
}

Do I have to call like an ‘update’ of the material after setting it?

3 Likes

You can’t change directly a material in the material array of the object. You need to get the array, change an array element, and send back the whole array to the MeshRenderer. In your case :

MeshRenderer myRend;
Material myBlinkMaterial;
void Start () {
   myRend = gameObject.GetComponent<MeshRenderer> ();
}
//called once we know we collided.
IEnumerator CollideFlash()
{
    Material[] materials = myRend.materials;
    materials[1] = blinkMaterial;
    materials[1].color = Color.white;
    myRend.materials = materials;
    Debug.Log("Name: " + myRend.materials[1].name);
    yield return new WaitForSeconds(0.1f);
    materials[1] = m;
    materials[1].color = c;
    myRend.materials = materials;
}
17 Likes

Thanks.