Restarting the game

There may come a time in a game when a player makes a mistake and would like to restart the level in the game they're currently playing. If you prepared your project ahead of time like we have, it's actually quite easy to get this functionality placed into your game. With that being said, let's implement that functionality now! We will perform the following steps:

  1. Select the Panel object and from there, create an empty child and drag it in the hierarchy to be the top child from the list. To that empty game object, rename it to Top Row and add a Horizontal Layout Group component to it.
  2. Next, drag and drop Resume object to it to make it a child and then duplicate it (Ctrl + D) to create a copy.
  3. As you can see, we now have two buttons on the same row.
  4. Rename the second Resume button to Restart and change the text to reflect that.
    Restarting the game
  5. Next, open up the PauseMenuBehaviour script and add the following line at the top of the file:
    using UnityEngine.SceneManagement; // LoadScene
    using UnityEngine;
  6. Then, add the following code as a new function:
    public void RestartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
  7. Next, have the Restart button now call this newly created RestartGame function.
  8. Once finished, save your file and move back into Unity and play the game! The following screenshot depicts the game screen:
    Restarting the game

Simple enough! We've now added a new button to our menu and when we click on it, we load the currently loaded level.

Note

If you use this implementation in your own projects, be sure to initialize all static variables inside your Start function unless you want them to be consistent between run-throughs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset