Adding Play Again Functionality in Unity

Harvey Limbo
1 min readApr 5, 2021

For today’s article, I’ll be following up on the Game Over Screen article and showing how I added in a way for a player to play the game by hitting the “R” key:

The Code

The above code checks if the current game state is in game over and enables the play again key which will reload the Game scene to when the game first started playing. In order to use the SceneManager class, the GameManager class needs the UnityEngine.SceneManagement dependency.

In the Player script, I call the ToggleGameOver(true) function when the number of lives left is 0:

// Player.cs - inside of Damage() function
// Delete Player if no more lives left
if (lives < 1)
{
uiManager?.ToggleGameOver(true);
Destroy(gameObject);
}

The ? in front of uiManager is a null-conditional operator. It is short for the following line of code:

if(uiManager != null)
{
uiManager.ToggleGameOver(true);
}

It’s good practice to always null check dependencies within a component to ensure they exist within the current game scene. Not doing so will cause the game to throw NullReferenceException

Thanks for reading :)

--

--