For example, I have a Game class and it keeps an int
that tracks the player's lives. I have a conditional
if ( mLives < 1 ) {
// Do some work.
}
However this condition keeps firing and the work is done repeatedly. For example, I want to set a timer to exit the game in 5 seconds. Currently, it will keep setting it to 5 seconds every frame and the game never ends.
This is just one example, and I have the same problem in several areas of my game. I want to check for some condition and then do something once and only once, and then not check or do the code in the if-statement again. Some possible solutions that come to mind are having a bool
for each condition and set the bool
when the condition fires. However in practice this gets very messy handling lots of bools
, since they have to be stored as class fields, or statically within the method itself.
What is the proper solution to this (not for my example, but for the problem domain)? How would you do this in a game?