Search Unity

Changing MeshRenderer Materials at Runtime

Discussion in 'Scripting' started by Studio_Akiba, Feb 27, 2017.

  1. Studio_Akiba

    Studio_Akiba

    Joined:
    Mar 3, 2014
    Posts:
    1,422
    I have changed MeshRenderer materials before, but never on an object with multiple material ID's, and I am having a little trouble achieving this.

    I assumed it was as straight-forward as assigning to an array with an int, but that doesn't appear to be working.

    The script is designed to toggle a light and an object's material on and off, simulating a bulb switching on and off in a flickering manner.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [System.Serializable]
    6. public class LightFlickerArray
    7. {
    8.     public MeshRenderer lightObject;
    9.     public int material = 0;
    10. }
    11.  
    12. public class LightFlicker : MonoBehaviour
    13. {
    14.     public GameObject light;
    15.     public Material onMaterial;
    16.     public Material offMaterial;
    17.     [SerializeField]
    18.     public LightFlickerArray[] lightObjects;
    19.  
    20.     void Update()
    21.     {
    22.         if (Random.value > 0.9)
    23.         {
    24.             if (light.activeSelf == true)
    25.             {
    26.                 light.SetActive(false);
    27.                 foreach(LightFlickerArray lfr in lightObjects)
    28.                 {
    29.                     lfr.lightObject.materials[lfr.material] = offMaterial;
    30.                 }
    31.             }
    32.             else
    33.             {
    34.                 light.SetActive(true);
    35.                 foreach (LightFlickerArray lfr in lightObjects)
    36.                 {
    37.                     lfr.lightObject.materials[lfr.material] = onMaterial;
    38.                 }
    39.             }
    40.         }
    41.     }
    42. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    From the docs:
     
  3. Studio_Akiba

    Studio_Akiba

    Joined:
    Mar 3, 2014
    Posts:
    1,422
    Seems like a needlessly complicated system, but thanks, it's working now :D