How to assign array to renderer.Materials

I write the following code to test assigning an array to renderer.Materails property.

var material0 = gameObject.renderer.material;
var material1 = new Material(material0);
var material2 = new Material(material0);
var materials = new Material[3];
var materials1 = materials;
materials[0] = material0;
materials[1] = material1;
materials[2] = material2;

gameObject.renderer.materials = materials;
Debug.Log(materials[0] == material0); //true
Debug.Log(materials[1] == material1); //true
Debug.Log(materials[2] == material2); //true

Debug.Log(materials[0] == gameObject.renderer.materials[0]); //true
Debug.Log(materials[1] == gameObject.renderer.materials[1]); //false
Debug.Log(materials[2] == gameObject.renderer.materials[2]); //false

how could the last two comparations can be false?

That’s easy: The material or materials property will create a copy of the materials you assign. Since your first material is already the copy (you read it back from the renderer) it will stay the same. The other two materials are copied.

You might want to use sharedMaterials instead. This will assign the material directly. But be careful. When changing anything on the material, all objects that have this material are affected.

Just as a side note: The materials shown in the inspector at edit time are the sharedMaterials. When running the game you will see the instance copies of the selected renderer