Pausing & Quitting the game in Unity
(Quitting in the Editor with seven additional lines of code!)
Day 29 — Aspiring Game Creator
2D Game Dev: Galaxy Shooter
Objective: Add the functionality for the typical “ESCAPE” key pressed.
If there’s ONE constant in all video games, it’s got to be the ESCAPE/PAUSE key — exceptions to the rule but it exists in nearly every game.
Adding this functionality of pausing the game is like every other in that it has to be programmed.
Luckily, Unity has made it extremely simply to both capture the key press and pause the game.
The most fundamental implementation is:
In almost every case using the time scale will be sufficient and that’s one reason why all movement should be Units Per Second (Time.deltaTime) rather than Units Per Frame (some fixed frame multiplier) only time based and physics are paused.
Changing to a multiplier rather than time.deltaTime and pausing the game doesn’t affect these game objects because they’re not using time to animate.
Below, the enemy’s movement has been altered to remove time and use frames so enemy ships will still move when the time scale is zero. Also note that collisions (physics) are not called because time is zero, but as soon as the game is “unpaused” there is a collision and subsequent explosion.
A few notes about changing the time scale.
Time Scale does not affect Audio. If the game audio needs to be paused when pausing the game the AudioListener.pause = false;
can be used. And if there’s a need to play Pause Menu audio then pausing of the Audio Listener can be bypassed with AudioSource.ignoreListenerPause=true;
If there is a need to have animations playing while the game is paused then there are unscaled versions of the widely used time time variables.
Time.unscaledDeltaTime and WaitForSecondsRealTime can be used in place.
For animations there’s a setting to ignore the time scale too:
Finish up with the ability to QUIT the game without building.
Making use of the UnityEditor namespace will allow a ‘quit’ button to stop the application.
There’s a lot of code to post, but in terms of PAUSE/EXIT & ESCAPE below is the GameManager code.