0
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Try

Renderer rend = GetComponent<Renderer> (); 
rend.material = materialsCopy[0];
\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Dec 29 '15 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.