How to Get a GAME OVER in Unity

Games ought to provide an enjoyable experience even when the player fails to meet their goal. Game developers have a responsibility to make it clear that the game is now over. Right now, the game we’ve been working on just abruptly ends when the player runs out of lives.

We really need some “GAME OVER” text so that it’s clear the player has lost, and should try again. Let’s work on that today. First, we’ll need a new UI object with the purpose of showing that text. I’ve left the anchor in the center, increased the font size to 50, allowed the text to Overflow out of the textbox so it will always appear, and change the color of the text to white. I’ve also aligned the text in the exact middle of the text box.

As always, it’s a good idea to try scaling the screen to see how the new UI object is affected. Everything looks good here.

Of course, we don’t wan the GAME OVER text to be visible at the start. We can add some code to the UIManager script to fix this.

Here we add a new variable to store the text object and assign it in the inspector. Start will make sure the text begins “inactive” so it isn’t shown when the game begins. Instead, we set it to active when the player has no lives remaining.

The Player script calls this UpdateLives function when damaged.

Here’s the result of those additions to the code. The text suddenly appears when the player takes a lethal hit.

Now what if we want a little more “oomph” to this message? We could make it flash red so it really stands out. Since we want to change the color at precise times, a coroutine would be perfect for this. Let’s head back to the UIManager script and create one.

This new coroutine now handles activating the text, as well as creating a loop that will constantly change the text from white to red and back again. _textFlashDelay is a serialized variable that can set in the inspector. That delay must be greater than a certain amount for the loop to work, so we avoid crashing Unity if the delay is set to zero.

Here’s the result when I set the _textFlashDelay to 0.4. Looks pretty good!

Now, how does the player restart the game once they’ve lost? That will be the topic for tomorrow!

I’m a passionate and talented software engineer seeking an opportunity in game development.