Unity How to Tell if Something Has Been Set Active Again

If you're making a game in Unity then, chances are, yous're going to demand a way to pause it.

This might exist to stop the game to brandish a message, to admission inventory or other game settings or to simply offer a traditional interruption menu to the role player.

Whatever it is, the benefits of being able to freeze gameplay temporarily volition be obvious to you.

But, what'southward the all-time fashion to do information technology?

Luckily, in that location's a simple option.

Then… what'south the best method for pausing the game in Unity?

The nigh convenient method for pausing the game in Unity is by setting the game'southward time scale to aught (Fourth dimension.timeScale = 0), which finer pauses all time based operations including motion, physics and animation. Setting the time scale to 1 again will return the game to its normal speed.

In well-nigh cases merely setting the time scale to nix to pause your game will be all you need to exercise.

However…

While near operations will exist paused when using this method, non everything in the game will exist affected.

In some cases, this is by design, for example when designing pause menus that nevertheless demand to motion and breathing.

Other times, all the same, it'south possible to accidentally exclude in-game objects from being paused properly.

In this post, I'll be exploring what is and is not affected past a time scale pause, how to exclude certain objects from being stopped as well as helping you to avoid some common pitfalls when pausing and unpausing your game.

Let'southward go started.

What you'll find in this article:

  • How to suspension the game in Unity (using time scale)
  • What does and doesn't get paused
  • How to pause 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 prevent command input when the game is paused
  • How to pause all audio when the game is paused
  • How to pause the game without using fourth dimension scale

How to pause the game in Unity (using fourth dimension scale)

To suspension a game in Unity, but set up the fourth dimension calibration to zero to suspension it and back to one (the default) to unpause it once again.

In scripting it looks like this:

          void PauseGame ()     {         Time.timeScale = 0;     } void ResumeGame ()     {         Time.timeScale = 1;     }        

How does information technology work?

Setting the time calibration affects the time and delta time measuring variables in the Time class.

Put simply, irresolute the time scale from its default of i will speed up or irksome the game down – for instance, yous can run the game at one-half speed with a time scale of 0.5, or twice equally fast with a timescale of 2). Setting information technology to null, pauses the game entirely.

Withal, not everything is affected.

Understanding what actually happens when the game is paused using this method will aid you to avoid unexpected behaviour later on.

What does and doesn't become paused

Stopping the game using time scale volition, effectively, pause every object that is time-based.

This typically accounts for everything that is happening in the game, as motion is commonly scaled past delta time, animation, also, is time-based and physics steps will non be called when time scale is zero.

Simply not everything is stopped, and understanding what'southward happening behind the scenes can help to make building a pause organization a little bit easier.

Update will keep to be called

It may surprise you to know that Update volition continue to exist called when the game's fourth dimension calibration is at zero.

This means that anything within of an Update loop, including in coroutines, will continue to run regardless of the time calibration, which can potentially cause an issue when detecting input (more on that later).

Nevertheless, annihilation that relies on time-based measurement will exist stopped, such as animations, fourth dimension-based delays such as Invoke and Wait for Seconds and all movement, so long as it'southward beingness multiplied by Time.deltaTime.

In practice, this means that, in most cases, everything will be stopped when the game is paused and, fifty-fifty though Update is still existence called, nothing is really happening.

FixedUpdate doesn't go chosen at all

How to Pause Physics in Unity - visualisation of objects falling in the editor

When Time.timeScale is set up to zero, Physics Steps (Fixed Update) will not exist called.

When the time scale is set to zero, Fixed Update will not be called at all.

This is useful as information technology substantially freezes all physics-based movement automatically whenever the game is paused using the fourth dimension calibration method.

Time will be stopped

When the time calibration is gear up to zilch, Time.time, which is the fourth dimension in seconds since the game started, volition exist stopped.

In most cases, this is a good affair, as any in-game measurement that relies on the Time.fourth dimension value will also be paused with it.

But what if you still demand to measure out time when the game is paused?

Luckily there are a couple of options for doing but that.

Time.realtimeSinceStartup and Time.unscaledTime are not afflicted by time calibration and will continue to measure time even when the game is paused.

Delta time based movement volition exist stopped

When the time scale is prepare to zero, all move will exist stopped, but only if that movement is being calculated in units per 2nd (using Time.deltaTime).

What does that mean?

In Unity it's practiced practice to multiply movement calculations by Time.deltaTime, which is the corporeality of time since the last frame. Similar this:

          void Update() {   gameObject.transform.Interpret(Vector3.down * Fourth dimension.deltaTime); }        

This converts the rate of movement from units per frame to units per 2d.

It's likely that you're already familiar with this concept, as it's used frequently when performing all kinds of actions over a period of time. The purpose being to maintain consequent, smooth movement, even when the frame rate changes (which it volition).

Merely there's another reason to use Time.deltaTime when moving objects.

When pausing the game using the time scale method, instead of the fourth dimension since the terminal frame, Time.deltaTime will be nothing.

This ways that whatsoever movement that is being multiplied past Time.deltaTime, will exist multiplied by zip. Which means no movement at all.

Usually, this is the desired behaviour when the game is paused.

If, nonetheless, you lot were to move an object using a fixed multiplier, like this:

          void Update() {   // Don't practice this!   gameObject.transform.Interpret(Vector3.down * 0.02f); }        

In this example, the object would continue to move, fifty-fifty when the game is paused.

Simply what if you actually do want this behaviour?

For case, what if yous want to intermission the entire game, except for some objects.

What's the correct way to do that?

How to pause everything in the game except for certain objects

When pausing the game, you may want some objects to continue to move without being affected past the alter in fourth dimension scale.

Luckily, it's possible to foreclose objects from being paused by using unscaled time in place of regular time variables.

For case, to apply unscaled time:

  • Instead of Time.deltaTime, employ Time.unscaledDeltaTime
  • Instead of Fourth dimension.fixedDeltaTime utilize Fourth dimension.fixedUnscaledDeltaTime
  • Instead of Fourth dimension.time, use Fourth dimension.unscaledTime

Almost variables in the Fourth dimension class include an unscaled option that, when used, will ignore changes to the fourth dimension scale.

Which is ideal for excluding certain objects from being paused, or from other time scale changes every bit well.

How to utilise a coroutine when the game is paused

Most coroutines will be frozen when the game is paused.

The coroutine itself isn't actually suspended.

Instead, the timing elements of the coroutine, such as while loops, Fourth dimension.deltaTime and WaitForSeconds, cannot complete and are preventing the coroutine from finishing.

Just what if you want to utilise a coroutine when the game is paused?

Just like in the previous example, replacing Time.deltaTime with Time.unscaledDeltaTime will allow the coroutine to run on unscaled time.

There'south also a replacement for WaitForSeconds: WaitForSecondsRealtime, which volition operate independent of fourth dimension scale changes, allowing the coroutine to run as normal, even when the game is paused.

Animated pause message in Unity game

Apply unscaled time to animate menus when the game is paused.

When building a pause menu, it's likely that your menu screen, buttons and controls volition all apply blitheness.

In that location's just i trouble…

Blitheness is time-based and when pausing the game using the fourth dimension calibration method, any menu animations will be paused too.

Luckily there'south an easy solution, by changing the Update Mode of the Animator component to use Unscaled Fourth dimension.

Unity Animations using Unscaled Time

Selecting Unscaled Time volition prevent animations from being paused. Nifty for menus!

The unscaled time update mode ignores time calibration changes and is ideal for animative suspension menus and other GUIs.

How to forbid control input when the game is paused

While movement volition exist stopped when the game is paused, Update volition keep to be called.

This tin crusade control input weather (which are often placed inside the Update loop) to however exist checked, fifty-fifty when the game is stopped.

In some cases, this isn't a problem.

Either because the movement tin can't occur or, in the case of physics-based motility, won't be chosen at all, equally Fixed Update is not chosen when fourth dimension calibration is at zippo.

Withal…

Allowing gameplay input while the game is paused can cause yous bug.

For case, in a peak-downward 2D game, it might be that player controls may still change the grapheme sprite to face a dissimilar direction, even though the graphic symbol isn't moving.

Deportment and other controls may also even so fire, merely may not work correctly or at all, merely to then trigger when the game is unpaused over again.

The controls that movement the player, may also be required to navigate the interruption menu.

In any case, for these reasons and more, information technology's proficient practice to prevent gameplay input while the game is paused.

Then what's the best way to do it?

The simplest method is to commencement keep track of whether the game is paused or not with a public static boolean variable, like 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 = 1;         }     } }        

Making the variable static means that it is non specific to a single instance (the value is always the same, fifty-fifty if there are multiple instances) and that any grade tin can access information technology.

Next, identify all of the game's input checks within if weather condition, so that they can but occur if the game is not paused, similar this:

          public class Jump : MonoBehaviour {     void Update()     {         if (!PauseControl.gameIsPaused)         {             if (Input.GetKeyDown(KeyCode.Space))             {                 // Make the player bound!             }         }         else         {             if (Input.GetKeyDown(KeyCode.Space))             {                 // Player can't jump! (The game is paused)             }         }     } }        

Alternatively, you may want to employ a more full general condition, similar to the above, only 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 also for other purposes as well, such as cutscenes.

Adding this simple condition early on in development will make information technology easier to prevent unexpected behaviour after.

How to pause all sound in Unity

Audio Source in Unity game scene editor

Pausing the Audio Listener is the easiest way to suspension all of the audio in a Unity game.

If you lot've tried using fourth dimension scale to pause the game, you lot may have noticed that audio continues to play fifty-fifty when the game is paused.

The Audio DSP fourth dimension value, which is the sound system fourth dimension value used for Play Scheduled, will also continue despite the game being paused.

So how do you stop all of the game'south audio when the game is paused?

Helpfully in that location'due south a very piece of cake method for doing exactly that.

Pausing the Audio Listener volition pause all audio in the game, too as the audio DSP time value.

Simply ready Audio Listener Break to true when pausing the game, similar this:

          void PauseGame ()     {         Fourth dimension.timeScale = 0f;         AudioListener.break = true;     } void ResumeGame ()     {         Time.timeScale = one;         AudioListener.break = simulated;     }        

Sound that is paused using this method volition resume from where information technology left off when the Audio Listener is unpaused once again. Likewise, any sound that was scheduled to play using Play Scheduled will play at the correct fourth dimension after gameplay is resumed.

But what about carte du jour sounds and music?

What if you lot want to stop some sounds, but keep others playing?

Helpfully, y'all can instruct Audio Sources to ignore the Audio Listener Interruption land, like this:

          AudioSource.ignoreListenerPause=true;        

This will let special Audio Sources, such equally for your menu and UI sounds to continue to play, even though other sounds have been stopped.

How to pause the game without using time scale

Setting time scale to zero is, in virtually cases, i of the most constructive 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 1 project may non be right for another.

There are options available for doing this, with the well-nigh straightforward being to just bank check the game's pause state before running any gameplay scripts. This is similar to the method of preventing control input mentioned earlier.

However…

When reading more about why some people would prefer not to use the time calibration method, I was surprised to larn that near of the reasons why were related to not existence able to animate menus, move objects, play audio or run coroutines.

Which, as you now know, are all possible to do when using the fourth dimension scale method.

If information technology's only the example that y'all weren't enlightened that the Sound Listener could exist paused, or that blitheness could utilise unscaled time or that coroutines tin really exist used when the game is paused, and so the time calibration method may notwithstanding be the best option for you.

And then requite it a try.

Now I desire to hear from yous

How are you pausing your game? Are you using the time calibration method or something else?

Did it work, and did anything happen that you didn't expect?

And what do you lot know at present virtually pausing a game in Unity that others could benefit from?

Any it is, leave a comment beneath and let me know.

Image Attribution

  • Unity Logo © Unity Technologies

Get Game Development Tips, Straight to Your inbox

Get helpful tips & tricks and master game evolution basics the easy way, with deep-dive tutorials and guides.

My favourite fourth dimension-saving Unity avails

Rewired (the best input management arrangement)

Rewired is an input management asset that extends Unity'due south default input system, the Input Manager, calculation much needed improvements and support for modernistic devices. Put only, it'southward much more advanced than the default Input Manager and more than reliable than Unity's new Input Organization. When I tested both systems, I found Rewired to exist surprisingly easy to use and fully featured, so I tin understand why everyone loves it.

DOTween Pro (should be congenital into Unity)

An asset then useful, it should already exist built into Unity. Except information technology's not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You tin motility, fade, scale, rotate without writing Coroutines or Lerp functions.

Easy Save (in that location's no reason non to employ it)

Easy Relieve makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time information technology would have to build a save organisation, vs the cost of buying Easy Save, I don't recommend making your own save system since Easy Save already exists.

rosssommor60.blogspot.com

Source: https://gamedevbeginner.com/the-right-way-to-pause-the-game-in-unity/

0 Response to "Unity How to Tell if Something Has Been Set Active Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel