Assigning multiple materials to a gameobject through script?

Viewed 837

How do I assign multiple materials to a gameobject through c# script?

What I have tried so far is:

public GameObject go;
public Material Mat1;
public Material Mat2;
void Start()
{ 
     //this does not work
     go.GetComponent<Renderer>().materials[0] = Mat1; 
}
3 Answers

You cannot update the materials directly, but you need to create a new materials array and assign it.

void Start()
    {
        //create your materials
        var yourMaterials = new Material[] { Mat1, Mat2 };
        //assign it
        go.GetComponent<Renderer>().materials = yourMaterials ;
    }

You may also check the documentation.

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.

From the documentation:

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.

Renderer rend = go.GetComponent<Renderer>();
Material [] mats = rend.materials;
mats[0] = Mat1;
rend.materials = mats;

if you want to change multiple materials you need to change the whole array. so you first create an array of materials with the same length as the current renderer:

Material[] newMaterials = renderer.sharedMaterials;
for(int i = 0; i <newMaterials.Length; i++)
{
newMaterials[i] = theMaterialYouWantToSetX;
}

and then you assign the array to the renderer:

renderer.materials = newMaterials;
Related