ColorListLerp

Something I’ve been interested in doing for my game is having a smooth lerp (linear interpolation) for a list of multiple colors. This kind of effect can be used for anything from health bars to sunsets. Out of the box, you get a LERP from one color to another. However, if you want to do more than one transition, (ex: Red -> Yellow -> Blue), you have to write some code.

Here’s the function I came up with:


//colorList = list of n colors
//val = ratio of time 0 - 1
public Color getColorLerp(List colorList, float val)
{
if (colorList.Count > 0)
{
float interval = 1f / (float)(colorList.Count-1);
int index = (int)((colorList.Count-1) * val);
float newVal = (val - (interval * index)) / interval;
if (index < 0) { return colorList[0]; } else if (index < colorList.Count - 1) { return Color.Lerp(colorList[index], colorList[index + 1], newVal); } else { return colorList[colorList.Count - 1]; } } else { return Color.White; } }