Skip to content

[Unity] How to Make “PAUSE” Function

Many games have the pause function that is convenient for players to interrupt the game if there are other important things while playing, and continue the game after returning.

In Unity, if you want to make this function is very easy.

  • Stop the game time
  • Pop up the pause menu (It can be very complicated or very simple)
  • Let the game time flow back to normal

The following I record of how to do these functions in Unity.


Make the pause menu

In the first, I recommend to make the pause menu, because it can hint us the game is pause or not. I make a simple pause text component for demo.

I also added a transparent black mask.

The mask component needs to be deactivate in the normal game but activated when it is paused.


Stop the game time

We need to create a GameManager game object, and attach the GameManager.cs script.


The script content is as follows:

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;


public class GameManager : MonoBehaviour
{
    // Pause UI
    public Button PauseButton;
    public GameObject PauseWindow;
    private bool isPause;

    void Start()
    {
        isPause = false;
        PauseButton.onClick.AddListener(PauseGame);
    }

    void PauseGame()
    {
        isPause = !isPause;

        if (isPause == true)
        {
            PauseButton.image.sprite = Resources.Load<Sprite>("Sprites/resume");
            PauseWindow.gameObject.SetActive(true);
            Time.timeScale = 0;
        }
        else
        {
            PauseButton.image.sprite = Resources.Load<Sprite>("Sprites/pause");
            PauseWindow.gameObject.SetActive(false);
            Time.timeScale = 1;
        }
    }
}



Time.timeScale = 0 means the game time is not flowing, Time.timeScale = 1 means the game time is flowing normally.

Do not forget to put PauseButton and PauseWindow in the script filed in Unity.


Now, let's try it out to see the effect.


References


Read More

Tags:

Leave a Reply