Once the player has lost all lives, it is time to display a attention-grabbing game-over message.
Setting up the text element
Creating the To do so we create a UI text element by write clicking on our canvas. Let’s rename it Game_Over. We can also adjust the color, text size and font. If we have a very large text the horizontal and vertical overflow should be set to overflow. Just like any game object we can move it to the location we prefer.
We now need to let the game know when to display the text. We do not need it at the start, thus we can untick it in the inspector.
Adding a variable to our UI Script
Our next step is to create a variable in the UI Manager script.
We use a SerializeField so that we can associate our object with the variable in the Ui Manager script on the canvas object.
It is also good practice to set the object inactive in the Start() method.
Deciding when to show the message
We do however want to show the text when the player is dead. Thus if the lives are zero then the object must become active. In code this looks like this:
When we try the game in Unity, we will now get a game-game over message as soon as there are 0 lives, indicated by the three empty ships.
Adding an attention-grabbing flicker
What if we want our game to give one of these old style blinking game-over texts?
There are different ways to achieve this. We can use coroutines. When current lives are zero, then we start a coroutine that turns the text on and off.
The coroutine simply shows the text for 0.5s and then shows no text for another 0.5s. We can use a while loop safely here as we start the coroutine with the condition that our current lives are zero.
Simple but effective…