Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to access second material in object

Discussion in 'Scripting' started by LuigiNicastro, May 8, 2020.

  1. LuigiNicastro

    LuigiNicastro

    Joined:
    Feb 7, 2018
    Posts:
    34
    I'm trying to change the second material in all objects in my array. I'm currently using


    Code (CSharp):
    1. for (var i = 0; i < structure.Length; i += 1)
    2.         {
    3.             structure[i].GetComponent<Renderer>().material = mats[0];
    4.         }


    This only changes the first material but I want it to change the second. When I do:



    Code (CSharp):
    1. for (var i = 0; i < structure.Length; i += 1)
    2.         {
    3.             structure[i].GetComponent<Renderer>().materials[1] = mats[0];
    4.         }


    Nothing happens. Does anyone have any ideas?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    Your second code block is really close... what you have to do is copy out the entire array of Materials, then change the one you want, and put it back.

    Code (csharp):
    1. var myRenderer = structure[i].GetComponent<Renderer>();
    2.  
    3. // copy it all out
    4. var TempArray = myRenderer.materials;
    5.  
    6. // change the one(s) you want to change
    7. TempArray[1] = mats[0];
    8.  
    9. // put it back
    10. myRenderer.materials = TempArray;
     
    PraetorBlue likes this.