Is there a way to programmatically pause the game (triggering all MonoBehaviour.OnApplicationPause() callbacks) ?
Hi,
Looking for the best way to pause the game.
Intuitively, I expected Application class to provide Pause() / Resume() methods to have MonoBehaviour-s paused / resumed (just like when hitting Editor's pause button).
Answer by UnityCoach · Mar 02, 2017 at 02:08 PM
OnApplicationPause is a message that a MonoBehaviour can use to handle when the application loses focus or is put in background.
Usually, to pause the game, you want to use a GameState enum, with a static property along with an event so that any component can subscribe to it, like :
public enum STATE
{
Running,
Paused,
Over
}
public delegate void StateChange(STATE state) ;
static public event StateChange StateChanged;
static private STATE _state;
static public STATE State
{
get { return _state; }
set
{
if (value != _state)
{
_state = value;
switch (_state)
{
case STATE.Running:
Time.timeScale = 1;
break;
case STATE.Paused:
Time.timeScale = 0;
break;
case STATE.Over:
Time.timeScale = 0;
break;
default:
break;
}
if (StateChanged != null)
StateChanged(_state);
}
}
}
Doesn't Time.timeScale also affect AudioSources? What if the player wants to pause without cutting off the music?
No, Time.timeScale only affects the value returned by Time.deltaTime and Physics. That's why you always want to multiply translation and other transformations by Time.deltaTime, so that it's frame rate independent, and is affected by timeScale.
If you want to pause music, you need to handle this too.
Hmmm.... I am still feeling like using Time to dictate pause state is only the proper solution for true "freeze the world" pausing scenarios. In situations where the game pauses while the player opens up a detailed menu system, it seems like that approach is too heavy-handed.
Your answer
Follow this Question
Related Questions
Using interfaces and Monobehaviour behaviours 0 Answers
Can't move camera when scipt's attached to chosen gameobject 1 Answer
exception for pause 1 Answer
Unity Monodevelop Error - All Scripts are Broken 0 Answers
Is it possible to hooking Unity engine? -1 Answers