Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 1 down vote accepted

Try

Renderer rend = GetComponent<Renderer> (); 
rend.material = materialsCopy[0];
share|improve this answer
    
Thanks. Had a hard time getting this working – Shantanu Singh Dec 29 '15 at 18:17
1  
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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