How to Lerp Colour in Unity

In by John FrenchPublished

It’s possible to change the value of a colour over time, or blend two colour values together, using Lerp.

Just like other Lerp functions, Color.Lerp involves setting a start colour, a target colour, and passing in a blend value, T, to weight between them.

This can be used to mix between two colours.

Like this:

float mix = 0.5f;
Color mixed color = Color.Lerp(colorA, colorB, mix);

Or, more typically, you can use it to blend from one colour to another over a period of time.

Like this:

public class LerpMaterialColour : MonoBehaviour
{
    public Color targetColor = new Color(0, 1, 0, 1); 
    public Material materialToChange;

    void Start()
    {
        materialToChange = gameObject.GetComponent<Renderer>().material;
        StartCoroutine(LerpFunction(targetColor, 5));
    }

    IEnumerator LerpFunction(Color endValue, float duration)
    {
        float time = 0;
        Color startValue = materialToChange.color;

        while (time < duration)
        {
            materialToChange.color = Color.Lerp(startValue, endValue, time / duration);
            time += Time.deltaTime;
            yield return null;
        }
        materialToChange.color = endValue;
    }
}

See also