Search Unity

How to access second material in object?

Discussion in 'General Discussion' 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>().material[1] = mats[0];
    4.         }


    I get an error. Does anyone have any ideas? I saw online someone said do render.material[1] but I don't know how to make that work in the current code I have.
     
    KarlKarl2000 likes this.
  2. MDADigital

    MDADigital

    Joined:
    Apr 18, 2020
    Posts:
    2,198
    sharedMaterials is probably the one you want to use.
     
  3. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,572
  4. MDADigital

    MDADigital

    Joined:
    Apr 18, 2020
    Posts:
    2,198
    Materials will clone material so it depends on what you wanna do. If you want to use same material (benefit from batching etc) you need to use sharedMaterials, otherwise you end up with a clone.

    If you change the sharedMaterial it will change for all, so it depends on what you want todo.