- Home /
How to change the color of an image every two seconds
I have a list of colors, and i want to change the color every two seconds to the next color in the list. This is the Code:
foreach(var item in rightAnswer) { StartCoroutine(ChangeImageColor(item)); }
And this is the Coroutine:
IEnumerator ChangeImageColor(string color) {
if(color == "red")
{
image.color = new Color32(255, 0, 0, 255);
}
else if (color == "orange")
{
image.color = new Color32(255, 140, 0, 255);
}
else if (color == "yellow")
{
image.color = new Color32(255, 255, 0, 255);
}
else if (color == "green")
{
image.color = new Color32(0, 255, 0, 255);
}
else if (color == "blue")
{
image.color = new Color32(0, 0, 255, 255);
}
else if (color == "purple")
{
image.color = new Color32(139, 0, 139, 255);
}
yield return new WaitForSeconds(2f);
}
Answer by HellsHand · May 07, 2021 at 07:02 PM
You don't want to run your Coroutine in a loop like that. What's happening right now is you are starting a Coroutine for every iteration of your loop so after 1 frame you have [rightAnswer.Length] amount of Coroutines all trying to change the objects color to a different color. You should send rightAnswer
to your Coroutine and then loop through inside of your Coroutine.
StartCoroutine(ChangeImageColor(rightAnswer));
IEnumerator ChangeImageColor(string[] item) {
foreach(var color in item)
{
if(color == "red")
{
image.color = new Color32(255, 0, 0, 255);
}
else if (color == "orange")
{
image.color = new Color32(255, 140, 0, 255);
}
else if(etc...) {}
yield return new WaitForSeconds(2f);
}
}
It functions now, but there´s a weird flicker that gives you nightmares. Any help?
No I'm sorry, can't say for sure why you would get a flicker. You are only running the Coroutine once right, no loops?
Np, i´m calling the coroutine in the Update Function under "else", but i don´t know if that has something to do with it. Maybe its called every frame because of the update function (???), but even if, i unfortantly dont know how to fix it. Thanks a lot anyways, and i´m sorry for my english...