Adventures in GameDev with GameDevHQ! Day 26: Creating a Retro Game Over Behavior!
As you may have noticed from yesterday when the ship gets damaged a third time, it just disappears and everything stops. We need to tell the player the game’s over! And we’ll do it 80s style with flashing text! Unfortunately, since we’re coding a videogame with a real coding language and not HTML, we just can’t stick a <blink> command. Oh wait, that’s been deprecated too! It just goes to show if you want blinking text, you’re going to have to do it yourself. Now if there were only some sort of command that helps us delay time before executing another…
That’s right! We’re going to be using Coroutines to simulate blinking text! Let’s do it!
First, we’re going to need to add a new Text object to the canvas. name it Game_Over_Text or anything similar. Anchor it to the center and make it big. Play around with the text options until you find something you like.
Everything looking good? Great! Now turn it off. We’ll be turning it back on through code later.
Just for fun, let’s add an extra line that says “Press R to restart game!”
I won’t show it here since you already know what to do. :)
As always, make holder variables in the UIManager.
Now drag each item into them in the Inspector.
Now that we have a reference to them, I like to be safe and turn them off using the SetActive attribute.
This makes doubly sure they won’t appear even if we accidentally turn them on while we’re testing things. I put it in the Start function because this runs before everything else does.
Next, we want to turn it on when the player dies the last time, but first let’s create a function in the UIManager that turns the Game Over text on:
We should call it when the player dies the final time.
I’ve commented out the irrelevant stuff so you can see where the GameOverText is being called, right inside the if check to see if there are no more players left. So let’s see if it’s working. (I’ve set the players to 1 so we can go to the good parts faster!)
Yes! We have our Game Over screen! But it’s not blinking. Let’s do that with a coroutine:
Ok, now let’s work on our flicker routine:
Just like the powerup and enemy spawners, I put the flickering code in a semi-endless while loop. I created a boolean _canRestart variable that is set to true when GameOverText is called so it won’t flicker until it’s supposed to.
Inside of the while loop, we wait for 3/4 of a second before turning off the text, then wait for half a second before turning it on…wash…rinse…repeat!
COOL! Now there’s just one more thing we can do to make this even cooler!
Can you figure out what it does? Check out the action below for the answer!
The coroutine calls another coroutine that after 3 seconds, brings up the “Press R to Continue” Cool!
Tomorrow we’ll go into loading scenes in Unity and actually making that R key work!