Search code examples
c#timermonogame

C# - why is my countdown timer not working?


Am I missing something? I've got my timer:

private int timer = 10;

And in my Update class, I have it so that when the timer reaches 0, an object will move across the X-axis.

do { timer--; }
while (timer > 0);

if (timer == 0)
{
    object1X--;
}

When I hit run, absolutely nothing happens. I've tried changing the timer to 0, and still nothing. I have a fair amount of C# knowledge, more than enough to know that this should work. Maybe today is a brain-dead day and I'm missing something obvious... thank you in advance :)


Solution

  • The do-while statement runs the code inside the brackets before checking the condition. On the first iteration of the code, the while loop decreases the timer to 0, as expected, and then evaluates the logical expression in the if statement. Since it will be true, it will run your if statement once.

    However, on the second iteration, the code will decrement your timer again (from 0 to -1), and then stop decrementing it, since it is not greater than 0. Then, when your if statement runs, it evaluates the expression as false, because -1 != 0. It will continue decrementing the timer variable, but since 0 is greater than all negative numbers, it will never return to 0, and the logical expression in your if statement will never evaluate to true again.