Search code examples
unity-game-enginerendering

Unity emission isn't updating when I change the material


Emission works in my game so far (see here). I am trying to make my car blink a color every 1-5 seconds, for some reason when I change my material to the emissive material, the emission doesn't work.

Screenshots

Volume and Mesh renderer

Midway through the prosses of changing colors and emissions

Glow material

Normal material

And here is my code,

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Menu : MonoBehaviour {

    public Material glow_mat;
    public Material normal_mat;
    public float spin_speed;
    public SkinnedMeshRenderer renderer;
    public bool changing;
    public bool glow_change;
    public float change_amount;

    // Start is called before the first frame update
    void OnEnable() {
        StartCoroutine(changeColorStart());
    }

    IEnumerator changeColorStart() {
        yield return new WaitForSeconds(Random.Range(1, 5));
        glow_change = true;
        changing = true;
    }

    // Update is called once per frame
    void Update() {
        transform.Rotate(0, spin_speed * Time.deltaTime, 0);
        if (changing) {
            change_amount += Time.deltaTime * 2;//0.2s per 1
            if (change_amount > 1) {
                change_amount = 1;
            }
            renderer.materials[0].Lerp(glow_change ? normal_mat : glow_mat, glow_change ?  glow_mat : normal_mat, change_amount);
            if (change_amount == 1) {
                change_amount = 0;
                if (glow_change) {
                    glow_change = false;
                } else {
                    changing = false;
                    StartCoroutine(changeColorStart());
                }
            }
        }
    }
}

Solution

  • I got this to work, if you're wondering you need to put this code after a material change,

    mat.SetColor("_EmissionColor", targetColor);//Or whatever material change you have.
    mat.EnableKeyword("_EMISSION");//This is a bug in unity
    

    I found the answer on the unity docs, here.