gameObject color switching loop

I am fairly new to Unity and JavaScript so when trying to create a loop using if statements I had some trouble. I want my object turn white, wait 3 seconds, turn black and repeat. here is my code; the object does not switch color but just stay the same color, I have no error messages and the debug also does not show.

#pragma strict 
var flash = true; 
function FlashLoop () 
{
 if (flash == true) 
{ Debug.Log("true"); 
transform.renderer.material.color = Color.black; yield 
WaitForSeconds (3); 
flash = false; 
} 
else if (flash == false) 
{ Debug.Log("false");
 transform.renderer.material.color = Color.white; 
yield WaitForSeconds (3); 
flash = true; 
} 
}

You can’t write a loop with if statements only, you need a “for”, “foreach”, “while” or “do…while” statement, or a recursive fuction that starts itself again at the end.

Your code should look something like this with a while:

#pragma strict
var flash = true;

function FlashLoop ()
{
    while (true) // this kind of loops will run forever
    {
        transform.renderer.material.color = flash ? Color.black : Color.white;
        flash = !flash;
        yield WaitForSeconds(3);
    }
}

Or like this with recursion:

function FlashLoop ()
{
    transform.renderer.material.color = flash ? Color.black : Color.white;
    flash = !flash;
    yield WaitForSeconds(3);
    FlashLoop();
}

I code in C# so I haven’t tested it, but I guess it should work.

Note that I’ve simplified the “if else” code, but it does the same thing as yours, if “flash” is true the color is set to black, otherwise it’s set to white. The next line changes the “flash” value to the oposite of the current value.