AKA, more fun with text…
Today we add a ‘Game Over’ banner when our player runs out of lives. The approach is simple. We add the text to our Canvas just as we did our scoreboard and our player lives icons. But once we set it, we disabled it by unchecking the box next to the name field.
In our UI Manager code, we already have a place where we are counting the player lives. So, all we have to do is call a coroutine from there when we hit zero lives.
public void CurrentLives (int lives)
{
livesImage.sprite = livesSprites[lives];
if (lives == 0) { StartCoroutine(DisplayGameOver()); }
}
IEnumerator DisplayGameOver()
{
bool flash;
gameOver = true;
gameOverText.gameObject.SetActive(true);
while (gameOver)
{
yield return new WaitForSeconds(0.5f);
flash = gameOverText.gameObject.activeSelf ? false : true;
gameOverText.gameObject.SetActive(flash);
}
}
All we do is make use of two variables, one saying we are in a game over state and the other a boolean we keep switching between true and false so we can alternate enabling and disabling the text. The flash
boolean is managed by the ternary operator. When flash
is true, it resets itself to false. When it is false, it resets itself to true. This gives us our blinking ‘GAME OVER’ text.
Of course, we have a lot of things we can do here, and the code is more or less the same. How about one letter at a time?
IEnumerator DisplayGameOver()
{
gameOver = true;
gameOverText.gameObject.SetActive(true);
float delay = .4f;
while (gameOver)
{
yield return new WaitForSeconds(delay);
gameOverText.text = "G";
yield return new WaitForSeconds(delay);
gameOverText.text = "GA";
yield return new WaitForSeconds(delay);
gameOverText.text = "GAM";
yield return new WaitForSeconds(delay);
gameOverText.text = "GAME";
yield return new WaitForSeconds(delay);
gameOverText.text = "GAME O";
yield return new WaitForSeconds(delay);
gameOverText.text = "GAME OV";
yield return new WaitForSeconds(delay);
gameOverText.text = "GAME OVE";
yield return new WaitForSeconds(delay);
gameOverText.text = "GAME OVER";
yield return new WaitForSeconds(delay);
}
}
Or maybe with just a few points-n-clicks we just get silly with it…