How to properly lerp emission value of a material?

Hi,

I am currently trying to smoothly transition from one emission color to another, but haven’t been able to get it to work like I can with color.

I managed to lerp color perfectly using:

GetComponent<Renderer>().material.color = Color.Lerp(GetComponent<Renderer>().material.color, targetColor, Time.deltaTime/timeLeft);

But when I attempt to change the emission value, I’m find that it does not smoothly transition, but changes to the next color right before the next color transition begins. I am using HSB color because I’d only like to modify hue and saturation. Here is the code in question:

using UnityEngine;
using System.Collections;

public class LerpHueSaturation : MonoBehaviour {

    private float timeLeft;
    private HSBColor _targetColorHSB;

    private void Awake()
    {
        _targetColorHSB = HSBColor.FromColor(Color.white);
    }

    private void Update()
    {
        if (timeLeft <= Time.deltaTime)
        {
            // Assign target color
            GetComponent<Renderer>().material.color = _targetColorHSB.ToColor();
           
            // Set the target color to a random hue and saturation
            _targetColorHSB = new HSBColor(Random.value, Random.value, _targetColorHSB.b);
            timeLeft = 2.0f;
            Debug.Log("Starting new transition");
        }
        else
        {
            GetComponent<Renderer>().material.SetColor("_EmissionColor",
        HSBColor.ToColor(HSBColor.Lerp(HSBColor.FromColor(GetComponent<Renderer>().material.color), _targetColorHSB, Time.deltaTime / timeLeft)));

            // Update timer
            timeLeft -= Time.deltaTime;
        }
    }
}

Any insight as to what I’m doing wrong and how to get the desired effect?

Hey SUBZORK8K,

In this line here:

GetComponent<Renderer>().material.SetColor("_EmissionColor", HSBColor.ToColor(HSBColor.Lerp(HSBColor.FromColor(GetComponent<Renderer>().material.color), _targetColorHSB, Time.deltaTime / timeLeft)));

You are setting the EmissionColor, but lerping with the material.color.

1 Like

Thanks, can’t believe I overlooked that!

1 Like