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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class LightFlickerArray
{
public MeshRenderer lightObject;
public int material = 0;
}
public class LightFlicker : MonoBehaviour
{
public GameObject light;
public Material onMaterial;
public Material offMaterial;
[SerializeField]
public LightFlickerArray[] lightObjects;
void Update()
{
if (Random.value > 0.9)
{
if (light.activeSelf == true)
{
light.SetActive(false);
foreach(LightFlickerArray lfr in lightObjects)
{
lfr.lightObject.materials[lfr.material] = offMaterial;
}
}
else
{
light.SetActive(true);
foreach (LightFlickerArray lfr in lightObjects)
{
lfr.lightObject.materials[lfr.material] = onMaterial;
}
}
}
}
}