Changing object's material at runtime

I’m generating several game objects at runtime by instantiating a prefab. To complicate things, the prefab has 3 materials on it. I would like to change one specifically on each, the body paint material, with one I choose at runtime. Unity apparently keeps the materials in an Array, but I can easily see which one I would like to change with a quick

Debug.Log(this.gameObject.GetComponent<MeshRenderer>().materials[1]);

and this does confirm that .materials[1] is the one I want to change. But nothing happens. The material remains the default one with no errors given.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TruckColor : MonoBehaviour
{
    public Material black;
    public Material blue;
    public Material green;
    public Material orange;
    public Material red;
    public Material white;

    public List<Material> truckColors;
    int randomInt;

    void Start()
    {

        truckColors.Add(black);
        truckColors.Add(blue);
        truckColors.Add(green);
        truckColors.Add(orange);
        truckColors.Add(red);
        truckColors.Add(white);

        randomInt = Random.Range(0, 5);

        //Verifying I'm trying to change the right material
        Debug.Log(this.gameObject.GetComponent<MeshRenderer>().materials[1]);

        this.gameObject.GetComponent<MeshRenderer>().materials[1] = truckColors[randomInt];
    }

    void Update()
    {

    }
}

I can change the COLOR just fine with <MeshRenderer>().materials[1].color = Color.white but I would prefer to swap the materials for their smoothness and metallic properties all at once.

You’re super close.

This won’t work because of tricky property accessors that make a copy when you get them.

This means your change is done against the copy and then discarded.

For multiple materials, here is the magical mystery colorful tasty sauce that you want:

var mats = theRenderer.materials; // copy the array

mats[1].color = Color.Red; // baBAM!! red is more interesting!

theRenderer.materials = mats; // copy it back

Worked perfectly! Thank you :slight_smile:

1 Like