How to - Basic Pause System in Unity
That's it! Stickman Rick is ready to show his moves even when the game is paused! Creating a Pause system can be a little intimidating and confusing, just try to remember the following tips; * Disable the necessary inputs when the game is paused. for a Challenge! In the spirit of the GameDev.
Having trouble creating a Unity pause menu? GameDev.tv Unity student and forum Master Problem Solver, Miguel, is here to help!
Creating a Pause menu is one of those things I didn't know how complicated it was until I tried it, many claim it's really simple, but I disagree, specially in 2D games.
As you have probably seen all over the internet, to pause a game you only need to set Time.timeScale to 0, which in theory is right, so, let's try that and see how everything goes. I already have a small game with a character that shall be named Stickman Rick. Stickman Rick can move, jump and turn into Super Stickman Rick with the press of a button (I know that's "op", let the Game Designer deal with that).
Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
Time.timeScale = 0;
}
}This will surely pause Stickman Rick's endeavours, but this won't help him get back to his task. The player should be able to unpause the game, for that we need to implement an "if" statement, or even better, a Ternary Operator.
// 1 2 3 4
Time.timeScale = Time.timeScale <= Mathf.Epsilon ? 0 : 1;1) Value to set, 2)Condition, 3) Value if condition equals true, 4) Value if condition equals false.The Ternary Operator behaves as an "if" statement but written in a single line.
Usually a game has a Pause Menu, the project already has one, we only need to activate or deactivate accordingly.
First; I don't like that Mathf.Epsilon, let's change that to a bool that serves as a state, that way we'll be able to have more control.
Challenge Time and Hints!
In the "PauseSystem" script:
- Create a bool variable named "isPaused".
- Add a GameObject variable named "pauseMenu" that shows in the inspector.
- Set the value of the previously created "isPaused" variable.
- Enable or disable the "pauseMenu" game object accordingly.
null;
bool isPaused;
void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { isPaused = !isPaused; Time.timeScale = isPaused ? 0 : 1; pauseMenu.SetActive(isPaused); } }
This definitely works like a pause system, but in reality, it's not working yet, there are 3 bugs that need our attention. Did you find any?
Awake()
{
pauseSystem = FindObjectOfType<PauseSystem>();
}
void Update() { if (pauseSystem.GetIsPaused()) { return; } }
We are almost done. There's a third issue with the pause system we need to fix before we call it a day.
here.