Unity UI: Game Over and Restart Behavior

An important part of any game is to add some behavior when all lives are lost, such as displaying text: Game Over, and the other is to restart the level to continue playing.

To add game over text, we just need to add a UI text object and type the appropriate content into the text field. Then we need to figure out when to show it, how to make the text have a flashing effect, and how to restart the level to get back into the game. Let’s start with the pseudocode:

1) If the number of lives below one, then activate the Game Over text.
2) The text has to flash, this can be done by activating and deactivating the object alternately every half second or faster.
3) For the same conditions, show the Restart text.
4) If the user clicks R, we will reload the game scene.

Using simple method and coroutines we get a solution for first 3points.

Point 4 of the pseudocode can be solved with a simple condition that checks if someone clicked the R key and if the game is really over. Next, we load the game scene using the LoadScene method from the SceneManager class (remember to use the namespace: using UnityEngine.SceneManagement) and the scene name or scene number starting from 0. The information about the _isGameOver declaration is sent from the Player class using the SetGameOver method.

More about Unity UI at the following link: https://docs.unity3d.com/Manual/UIToolkits.html

--

--

Damian Dąbrowski

Hi, I’m Damian, a Unity Software Engineer who loves building education and simulation games.