Trying to build an array of materials

I have successfully grabbed the material off of an object, stored it so I could change it’s color and then reapplied it later. Doing this so I can highlight it on button click.

However, I have another object that has multiple materials and need them ALL to change color and back. Trying to figure out how I gather all the materials applied to the character and shove it into an array so that I can reapply them.

Quick example, I got a rock to turn from grey to red so that it can be highlighted then turns back to grey. But when I turn 2 warriors to red with the same code, one has a shield turn red and the other has it’s helmet turn red because they have numerous materials.

The basics of the code I’m using is as follows

private Material origMat; //to store the original material

public Material redMaterial; //so that I can store a red material to be applied

void Start() {

 origMat = this.GetComponent<Renderer>().material; //stores what the object has for a material;


and then on mouse click

this.GetComponent().material = redMaterial;

mouse click again

this.GetComponent<Renderer>().material = origMat;

I know I will need an if statement in start based on how many materials it has and store those into an array and then reapply them later in the same order. I also know that in Unity it says on the mesh renderer that these guys have 20 elements in the Materials drop down. But I’ve no clue how to grab that data from Unity.

So in summary, how do I grab and fill the array from multiple materials? Right now it only does element 0.

You will first need a reference to your characters Renderer.
You can get this by using the

  Renderer theRenderer =  GetComponent<Renderer>()

When you have the renderer you can get all applied materials like this:


This will return an array with all the materials on for instance your warrior.

Please note that you cannot change the materials directly in this property.

If you want to change one of these materials you need to save them into an array first, change what you want and then put it back into the .materials.

Something like this

Material[] allMaterials;
allMaterials = theRenderer.materials;

//Change the materials you want to change now
allMaterials[0] = yourMaterialHere
allMaterials[1] = yourSecondMaterialHere;

//Apply your changes back to your Renderer

theRenderer.materials = allMaterials;

Hope that helps!