- Home /
Question by
johnsyu · Mar 03, 2021 at 10:32 PM ·
materialsharedmaterialintantiate
sharedMaterial not working after instantiate
Hi, I have this script to change emission color for a material shared by objects that replace each other, however, the material reverts back to the original if the color is changed before the next object is instantiated. Ideally the change to material would be shared, and at runtime end, the .mat is not affected. Please help!
using UnityEngine; using System.Collections;
public class CycleEmissionColor : MonoBehaviour {
public Color[] colors;
public int currentIndex = 0;
private int nextIndex;
public float changeColourTime = 2.0f;
private float lastChange = 0.0f;
private float timer = 0.0f;
Renderer rend;
void Start()
{
GetComponent<Renderer>().sharedMaterial = new Material(GetComponent<Renderer>().sharedMaterial);
rend = GetComponent<Renderer>();
if (colors == null || colors.Length < 2)
Debug.Log("Need to setup colors array in inspector");
nextIndex = (currentIndex + 1) % colors.Length;
}
void Update()
{
timer += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
currentIndex = (currentIndex + 1) % colors.Length;
nextIndex = (currentIndex + 1) % colors.Length;
timer = 0.0f;
}
Color newColor = Color.Lerp(colors[currentIndex], colors[nextIndex], timer / changeColourTime);
GetComponent<Renderer>().sharedMaterial.SetColor("_EmissionColor", newColor);
}
}
Comment