# How to set material to gameobject dynamically using c# script in unity?

I want to set material to a gameobject in unity using c# script.

I am using this code to set the material of mesh renderer attached to the gameobject -

MeshRenderer mesh = gameObject.GetComponent<MeshRenderer>();
mesh.materials[0] = materialsCopy[0];


here materialsCopy is an array of type Materials which I've made public and I am attaching the Materials by drag & drop to the materialsCopy but when I run the game I get a white colored mesh instead of the set material of the 0 index materialsCopy. The 0 indexed materialsCopy has albedo set to an image. I want this image to get attached to the gameobject. How should I proceed ?

In addition to this I am also getting a warning - Tiled GPU perf. warning: RenderTexture color surface (0x0) was not cleared/discarded, doing

Renderer rend = GetComponent<Renderer> ();

• To give a bit more context about why this works: renderer.materials returns a copy of the internal materials array. So assigning renderer.materials[0] = foo only sets the first material of the copy. Assigning a material to renderer.material or assigning an array of materials to renderer.materials replaces the current contents, instead of modifying a copy. – DMGregory Dec 29 '15 at 18:17