Not exactly sure how to phrase the title but I want to generate a random color every second on an object. I also want this color to not be similar to the old color the object already has. If the current random color is the-same as the color the Object already has, re-generate the random color again. That object is simply a Text
component.
This is the function I use to generate the color:
public Color genRandomColor()
{
float r, g, b;
r = UnityEngine.Random.Range(0f, 1f);
g = UnityEngine.Random.Range(0f, 1f);
b = UnityEngine.Random.Range(0f, 1f);
return new Color(r, g, b);
}
For comparing if the color are similar, I ported and used the function from this answer to C#.
public double ColourDistance(Color32 c1, Color32 c2)
{
double rmean = (c1.r + c2.r) / 2;
int r = c1.r - c2.r;
int g = c1.g - c2.g;
int b = c1.b - c2.b;
double weightR = 2 + rmean / 256;
double weightG = 4.0;
double weightB = 2 + (255 - rmean) / 256;
return Math.Sqrt(weightR * r * r + weightG * g * g + weightB * b * b);
}
I put the random color generator in while
loop inside a coroutine function to run over and over again until the generated color is not similar. I use yield return null;
to wait for a frame each time I generate a random color so that it does not freeze the program.
const float threshold = 400f;
bool keepRunning = true;
while (keepRunning)
{
Text text = obj.GetComponent<Text>();
//Generate new color but make sure it's not similar to the old one
Color randColor = genRandomColor();
while ((ColourDistance(text.color, randColor) <= threshold))
{
Debug.Log("Color not original. Generating a new Color next frame");
randColor = genRandomColor();
yield return null;
}
text.color = randColor;
yield return new WaitForSeconds(1f);
}
Everything seems to be working with one minor problem.
The problem is that it takes 1
to 3
seconds to re-generate a color that is not a similar to the old one sometimes. I removed yield return null;
to prevent it from waiting each frame and it seems to work now but I risk freezing the whole game since I am now using the random function to control the while
loop. Already, I've noticed tiny freezes and that's not good.
What's a better way to generate a random color that is not similar to the object's new color without freezing the game or waiting for seconds?