Creating A Pause In Unity

Creating a pause function in unity is pretty easy to implement. It only takes a few simple lines of code yet it’s a commonly asked question, so I’ll show you a quick and easy way to implement pausing of your game in Unity.

Time.timeScale = 0f;

Time.timeScale is the scale of which time passes by in your application. Set it to 0 and any functions that are time dependent will stop. To un-pause, just do the opposite.

Time.timeScale = 1.0f;

Note that everything that is time dependent will stop, so any animations will stop moving as well. However, it’s likely that your pause menu and UI need to continue to animate even after the game is paused. You can fix this by setting those animations to update using Unscaled Time.

unity pause function

This is found in the Animator component of your game object. In this example, it’s for my main menu. I like my menus to drop down from the top of the screen when the game is paused, so they need to stay moving.

Here’s a simple snippet you can use to pause your game that saves the state in a boolean. The function toggles between paused and unpaused states, so you can use the same function throughout different parts of your game.

public bool isPaused;
 /**
     * Toggles game pause, returns state of the game after.
     **/
    public bool Pause()
    {
        if (isPaused)
        {
            isPaused = false;
            Time.timeScale = 1.0f;
        }
        else
        {
            isPaused = true;
            Time.timeScale = 0f;
        }
        return isPaused;
    }

Another useful way to use the isPaused boolean is to set it as a condition when getting player input. It’s likely you don’t want to player to be able to move the camera or character around when the game is paused, so you’ll need to stop that.

    void Update()
    {
        if (isPaused)
            return;     //returns if game is paused
    }

Note that FixedUpdate isn’t called when timeScale is set to 0
Anyways, that’s all there is to this simple method of pausing your game in Unity. Just remember that Update() isn’t affected by timeScale, so it’s still called as per normal. Thanks for reading and  happy coding!

Bonus: It might be a little finicky, but Time.timeScale can be used to speedup / slowdown time within your game. Since everything affected by time will be scaled by it, you could use it to create some slow-motion and speed-boosts as well. It affects your whole game though, so you may want to implement this using your own multiplier variable.

Interested in more Unity tutorials? Click here!

Recommended Posts

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Christian Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Christian
Guest
Christian

Thanks! This is very helpful!