How to change a single material on an object with multiple materials in Unity3D?

Issue

Please Help

#Problem

I have a 3d model having more then 1 material and i want to change material Element no 2 through c#
Look Image "Material Element Order"enter image description here

This is not working

  // Start is called before the first frame update
    public GameObject Cube;

    public Material Red;
    public Material Yellow;
    public Material ResultGreen;

    void Start()
    {
        Cube.gameObject.GetComponent<MeshRenderer>().materials[1] = ResultGreen;

    }

Solution

Renderer.materials is a property that either returns or assigns an array.

You can’t change one element of it directly / it makes no sence since what would happen is that you only exchange the element in the array returned by the property and then throw away that array. This would change nothing actually.

Or how Unity phrases it and actually tells you exactly what to do

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.

You rather have to do it like

// directly store the reference type you need most
public Renderer Cube;

private void Start()
{
    // get the current array of materials
    var materials = Cube.materials;
    // exchange one material
    materials[1] = ResultGreen; 
    // reassign the materials to the renderer
    Cube.materials = materials;
}

Answered By – derHugo

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.