It Seems Like the Right Game to Start Hutton Again
If yous're making a game in Unity then, chances are, you lot're going to need a way to suspension it.
This might be to end the game to display a message, to access inventory or other game settings or to simply offer a traditional pause menu to the role player.
Any it is, the benefits of beingness able to freeze gameplay temporarily will exist obvious to y'all.
But, what'south the best way to do it?
Luckily, there'due south a simple selection.
And then… what's the all-time method for pausing the game in Unity?
The most convenient method for pausing the game in Unity is by setting the game's fourth dimension scale to zero (Time.timeScale = 0), which effectively pauses all time based operations including motion, physics and animation. Setting the fourth dimension scale to ane once more will return the game to its normal speed.
In most cases merely setting the time scale to zero to pause your game will be all you need to do.
However…
While most operations will exist paused when using this method, not everything in the game will exist affected.
In some cases, this is by design, for example when designing intermission menus that however demand to move and animate.
Other times, however, it'southward possible to accidentally exclude in-game objects from beingness paused properly.
In this post, I'll be exploring what is and is not affected by a time calibration pause, how to exclude certain objects from being stopped as well every bit helping you to avoid some common pitfalls when pausing and unpausing your game.
Let's get started.
What yous'll observe in this article:
- How to suspension the game in Unity (using fourth dimension scale)
- What does and doesn't get paused
- How to suspension everything in the game except for certain objects
- How to use a coroutine when the game is paused
- How to animate menus and objects when the game is paused
- How to forbid control input when the game is paused
- How to intermission all sound when the game is paused
- How to pause the game without using time scale
How to pause the game in Unity (using fourth dimension scale)
To intermission a game in Unity, simply set the time scale to zero to break it and back to one (the default) to unpause it again.
In scripting it looks like this:
void PauseGame () { Time.timeScale = 0; } void ResumeGame () { Time.timeScale = 1; }
How does information technology piece of work?
Setting the time scale affects the time and delta time measuring variables in the Time class.
Put simply, irresolute the fourth dimension calibration from its default of ane will speed upward or boring the game down – for instance, you lot can run the game at half speed with a time scale of 0.5, or twice as fast with a timescale of two). Setting it to zero, pauses the game entirely.
Still, non everything is affected.
Understanding what actually happens when the game is paused using this method will assist you to avoid unexpected behaviour subsequently on.
What does and doesn't get paused
Stopping the game using fourth dimension scale will, finer, pause every object that is fourth dimension-based.
This typically accounts for everything that is happening in the game, every bit move is usually scaled by delta fourth dimension, animation, also, is fourth dimension-based and physics steps will non be called when time scale is zero.
But not everything is stopped, and understanding what's happening backside the scenes can aid to make edifice a interruption system a fiddling bit easier.
Update will keep to be called
It may surprise you to know that Update will go along to be called when the game'due south time calibration is at null.
This means that annihilation inside of an Update loop, including in coroutines, will keep to run regardless of the fourth dimension scale, which can potentially cause an issue when detecting input (more on that later).
All the same, anything that relies on time-based measurement will exist stopped, such every bit animations, time-based delays such as Invoke and Await for Seconds and all movement, then long as information technology's being multiplied by Time.deltaTime.
In practice, this means that, in most cases, everything volition exist stopped when the game is paused and, even though Update is yet being called, goose egg is actually happening.
FixedUpdate doesn't get called at all
When the time scale is set to zip, Stock-still Update will not exist called at all.
This is useful every bit information technology substantially freezes all physics-based movement automatically whenever the game is paused using the time scale method.
Time will be stopped
When the time calibration is prepare to zippo, Time.time, which is the time in seconds since the game started, will be stopped.
In most cases, this is a good thing, as any in-game measurement that relies on the Time.time value volition as well be paused with it.
But what if you still demand to measure time when the game is paused?
Luckily there are a couple of options for doing just that.
Time.realtimeSinceStartup and Time.unscaledTime are non affected past time scale and will continue to measure time even when the game is paused.
Delta time based movement will exist stopped
When the fourth dimension calibration is set to zippo, all movement will be stopped, only only if that movement is existence calculated in units per 2d (using Time.deltaTime).
What does that hateful?
In Unity information technology's good practice to multiply motion calculations by Fourth dimension.deltaTime, which is the amount of time since the last frame. Like this:
void Update() { gameObject.transform.Translate(Vector3.downward * Time.deltaTime); }
This converts the rate of movement from units per frame to units per second.
Information technology's probable that yous're already familiar with this concept, equally information technology'southward used often when performing all kinds of actions over a period of fourth dimension. The purpose being to maintain consistent, smooth motility, fifty-fifty when the frame rate changes (which it volition).
But there'south another reason to use Time.deltaTime when moving objects.
When pausing the game using the time calibration method, instead of the fourth dimension since the last frame, Time.deltaTime will be nada.
This ways that any movement that is being multiplied by Time.deltaTime, will be multiplied by nothing. Which means no movement at all.
Commonly, this is the desired behaviour when the game is paused.
If, however, you were to movement an object using a fixed multiplier, similar this:
void Update() { // Don't do this! gameObject.transform.Translate(Vector3.downward * 0.02f); }
In this example, the object would continue to move, even when the game is paused.
But what if you actually exercise want this behaviour?
For example, what if yous want to suspension the entire game, except for some objects.
What'southward the right way to practise that?
How to pause everything in the game except for certain objects
When pausing the game, you may want some objects to proceed to motion without existence affected past the change in time scale.
Luckily, information technology's possible to prevent objects from being paused by using unscaled fourth dimension in place of regular time variables.
For example, to use unscaled time:
- Instead of Time.deltaTime, use Time.unscaledDeltaTime
- Instead of Fourth dimension.fixedDeltaTime utilise Time.fixedUnscaledDeltaTime
- Instead of Time.time, use Fourth dimension.unscaledTime
Near variables in the Time grade include an unscaled option that, when used, volition ignore changes to the time calibration.
Which is ideal for excluding certain objects from being paused, or from other time scale changes besides.
How to use a coroutine when the game is paused
Most coroutines will exist frozen when the game is paused.
The coroutine itself isn't actually suspended.
Instead, the timing elements of the coroutine, such every bit while loops, Time.deltaTime and WaitForSeconds, cannot consummate and are preventing the coroutine from finishing.
But what if y'all want to use a coroutine when the game is paused?
Simply similar in the previous example, replacing Fourth dimension.deltaTime with Time.unscaledDeltaTime will allow the coroutine to run on unscaled time.
At that place'south also a replacement for WaitForSeconds: WaitForSecondsRealtime, which will operate independent of time scale changes, allowing the coroutine to run as normal, even when the game is paused.
When edifice a pause menu, information technology'south likely that your carte du jour screen, buttons and controls will all use animation.
There'due south simply one trouble…
Animation is time-based and when pausing the game using the fourth dimension scale method, whatsoever carte du jour animations will be paused besides.
Luckily there's an easy solution, by irresolute the Update Mode of the Animator component to utilize Unscaled Time.
The unscaled time update way ignores time scale changes and is ideal for animating break menus and other GUIs.
How to forbid control input when the game is paused
While movement will exist stopped when the game is paused, Update will continue to exist chosen.
This can cause control input conditions (which are ofttimes placed within the Update loop) to still exist checked, even when the game is stopped.
In some cases, this isn't a problem.
Either because the move tin't occur or, in the example of physics-based movement, won't be chosen at all, as Fixed Update is not called when time scale is at zero.
Notwithstanding…
Allowing gameplay input while the game is paused can crusade you problems.
For example, in a elevation-down second game, it might be that histrion controls may still change the grapheme sprite to face a different direction, even though the character isn't moving.
Deportment and other controls may also yet fire, simply may non work correctly or at all, merely to then trigger when the game is unpaused once more.
The controls that move the player, may besides be required to navigate the pause menu.
In any example, for these reasons and more, it's good practice to forbid gameplay input while the game is paused.
And so what'southward the all-time way to do it?
The simplest method is to first keep track of whether the game is paused or not with a public static boolean variable, similar this:
public class PauseControl : MonoBehaviour { public static bool gameIsPaused; void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { gameIsPaused = !gameIsPaused; PauseGame(); } } void PauseGame () { if(gameIsPaused) { Fourth dimension.timeScale = 0f; } else { Time.timeScale = one; } } }
Making the variable static means that information technology is non specific to a single instance (the value is always the same, even if in that location are multiple instances) and that any class can access it.
Next, identify all of the game's input checks within if conditions, so that they can just occur if the game is non paused, like this:
public grade Jump : MonoBehaviour { void Update() { if (!PauseControl.gameIsPaused) { if (Input.GetKeyDown(KeyCode.Infinite)) { // Make the player jump! } } else { if (Input.GetKeyDown(KeyCode.Space)) { // Player can't jump! (The game is paused) } } } }
Alternatively, you lot may want to use a more general status, similar to the above, but that controls all of the gameplay input, turning it on or off. This would let you to disable input when the game is paused and likewise for other purposes also, such as cutscenes.
Calculation this simple condition early in development volition make it easier to preclude unexpected behaviour afterwards.
How to break all audio in Unity
If you lot've tried using time scale to pause the game, you may take noticed that audio continues to play even when the game is paused.
The Audio DSP time value, which is the audio system time value used for Play Scheduled, volition besides go along despite the game being paused.
So how do you terminate all of the game's audio when the game is paused?
Helpfully there's a very like shooting fish in a barrel method for doing exactly that.
Pausing the Sound Listener will break all audio in the game, as well as the audio DSP time value.
Simply ready Sound Listener Suspension to true when pausing the game, like this:
void PauseGame () { Time.timeScale = 0f; AudioListener.pause = true; } void ResumeGame () { Time.timeScale = 1; AudioListener.pause = false; }
Audio that is paused using this method will resume from where it left off when the Sound Listener is unpaused once again. Likewise, any audio that was scheduled to play using Play Scheduled will play at the correct time after gameplay is resumed.
But what about menu sounds and music?
What if you want to stop some sounds, simply keep others playing?
Helpfully, y'all can instruct Audio Sources to ignore the Audio Listener Break state, like this:
AudioSource.ignoreListenerPause=true;
This volition allow special Audio Sources, such as for your menu and UI sounds to go along to play, even though other sounds take been stopped.
How to break the game without using time calibration
Setting time scale to zero is, in about cases, one of the most effective and convenient methods for pausing the game in Unity.
Despite this, I've seen a number of questions from people asking how to pause the game without using the time scale method.
This is, of course, absolutely fine. What works for one project may not exist right for another.
There are options available for doing this, with the nigh straightforward being to just cheque the game'south pause country before running any gameplay scripts. This is like to the method of preventing control input mentioned earlier.
Yet…
When reading more about why some people would prefer non to utilise the time scale method, I was surprised to larn that nigh of the reasons why were related to not beingness able to breathing menus, motion objects, play audio or run coroutines.
Which, as you now know, are all possible to do when using the time scale method.
If information technology's but the case that you weren't aware that the Audio Listener could be paused, or that blitheness could apply unscaled time or that coroutines can actually be used when the game is paused, then the time scale method may yet be the best option for yous.
So give it a try.
Now I want to hear from you
How are you pausing your game? Are you using the time scale method or something else?
Did it piece of work, and did annihilation happen that you didn't look?
And what practise you know now virtually pausing a game in Unity that others could benefit from?
Whatever it is, leave a comment beneath and permit me know.
Image Attribution
- Unity Logo © Unity Technologies
My favourite time-saving Unity avails
Rewired (the best input management system)
Rewired is an input management nugget that extends Unity'due south default input system, the Input Manager, calculation much needed improvements and support for modern devices. Put simply, it'south much more avant-garde than the default Input Manager and more reliable than Unity'south new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I tin understand why anybody loves it.
DOTween Pro (should be built into Unity)
An asset and then useful, it should already exist built into Unity. Except it'south not. DOTween Pro is an animation and timing tool that allows you to animate annihilation in Unity. Y'all can move, fade, calibration, rotate without writing Coroutines or Lerp functions.
Easy Salve (there's no reason non to apply it)
Easy Relieve makes managing game saves and file serialization extremely easy in Unity. And then much and then that, for the time it would take to build a save arrangement, vs the price of buying Easy Save, I don't recommend making your own save system since Easy Save already exists.
Source: https://gamedevbeginner.com/the-right-way-to-pause-the-game-in-unity/
0 Response to "It Seems Like the Right Game to Start Hutton Again"
Post a Comment