Pause Screen

MyGameManager.cs

Size: 1.81 KB

You need to login to download this file.

Canvas

  1. Create a new canvas called "Pause Canvas"
  2. Give it a text object for the titel
  3. A button to go back to the main menu
  4. Then disable the canvas

 

Game manager

  1. Create a empty object
  2. Add the MyGameManager.cs script
  3. Add all your canvases to the empty objects

 

Script

We start by checking if the "Escape" button is pressed in the Update function

 void Update()
    {
        // Pause screen
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            TogglePause();
        }

if the button is pressed it wil trigger the "TogglePause" function. This function will put the canvas on active and the timeScale on 0

This will stop everything, after pressing "Escape" again everything will be disabled and the timeScale back to 1. Everything will go back to normal

 // Pause screen
    public void TogglePause()
    {// Game is not paused
        if (Time.timeScale > 0)
        { // Pause the game
            Time.timeScale = 0; 
            pauseCanvas.SetActive(true);
            AudioListener.pause = true;
            Cursor.visible = true;
        }

        else if (Time.timeScale == 0)
        { // Unpause the game
            Time.timeScale = 1;
            pauseCanvas.SetActive(false);
            AudioListener.pause = false;
            Cursor.visible = false;
        }
    }

recommended