# Best way to mix color values?

right now i am using the halfway point of lerp to mix two colors:

``````startColor = Color.Lerp(Color.blue, Color.red, 0.5);
``````

but say i wanted to mix 3 colors at once, like red + blue + yellow

i have a feeling i am missing something very simple

The way you use lerp, all you’re actually doing is calculating the arithmetic mean. That means you can simply add all colors together and divide the result be the number of colors.

So your example is the same as:

``````    startColor = (Color.blue + Color.red) / 2;
``````

Note: With Color32 it doesn’t work that way, since each component is just a byte, so you can’t exceed the max value which Color can since each component is a float. However since Color can be implicit converted into Color32 and the other way round, you can do this calculation with Color.

Here’s a method which would combine multiple colors:

``````// C#
public static Color CombineColors(params Color[] aColors)
{
Color result = new Color(0,0,0,0);
foreach(Color c in aColors)
{
result += c;
}
result /= aColors.Length;
return result;
}
``````

This method can be used like this:

``````    startColor = CombineColors(Color.blue, Color.red, Color.yellow);
``````

startColor = (Color.blue + Color.red + Color.yellow) / 3.0;

float r = (color1.r + color2.r + color3.r) / (3f);
float g = (color1.g + color2.g + color3.g) / (3f);
float b = (color1.b + color2.b + color3.b) / (3f);

``````startColor = new Color(r, g, b, 1.0f);
``````

It works the same for the alpha, should you need that, as well.

I can provide these two functions that I found on the web. The first one is probably the relevant one.

``````public Color CombineColors(params Color[] aColors)
{
Color result = new Color(0,0,0,0);
foreach(Color c in aColors)
{
result += c;
}
result /= aColors.Length;
return result;
}

public Color TransformHSV(
Color color,  // color to transform
float H,          // hue shift (in degrees)
float S,          // saturation multiplier (scalar)
float V           // value multiplier (scalar)
)
{
float VSU = V*S*Mathf.Cos(H*Mathf.PI/180);
float VSW = V*S*Mathf.Sin(H*Mathf.PI/180);

Color ret = new Color();
ret.r = (.299f*V+.701f*VSU+.168f*VSW)*color.r
+ (.587f*V-.587f*VSU+.330f*VSW)*color.g
+ (.114f*V-.114f*VSU-.497f*VSW)*color.b;
ret.g = (.299f*V-.299f*VSU-.328f*VSW)*color.r
+ (.587f*V+.413f*VSU+.035f*VSW)*color.g
+ (.114f*V-.114f*VSU+.292f*VSW)*color.b;
ret.b = (.299f*V-.3f*VSU+1.25f*VSW)*color.r
+ (.587f*V-.588f*VSU-1.05f*VSW)*color.g
+ (.114f*V+.886f*VSU-.203f*VSW)*color.b;
ret.a = 1f;
if(ret.r < 0) {ret.r = 0;}
if(ret.g < 0) {ret.g = 0;}
if(ret.b < 0) {ret.b = 0;}
return ret;

}
``````