问:
What code do I need to make my game pause? How do I stop everything?
答1:
In the Editor, you can just click the pause button.
From gamecode, you can set Time.timeScale to 0. See the help entry. This should pause most of your game, assuming you don't rely on stuff like asking the actual system time. You can also set timeScale to anything between 0 and 1 (and even 1 and up), to modify the speed at which your gamesimulation progresses.
答2:
If you rely on the time to remain active during the pause you can also implement it a following way.
If an MonoBehaviour needs a pause action, like e.g. stopping the animation, implement an OnPauseGame() function. To handle resuming, implement an OnResumeGame() function.
When the game needs to pause, call the OnPauseGame function on all objects using something like this:
Object[] objects = FindObjectsOfType (typeof(GameObject));
foreach (GameObject go in objects) {
go.SendMessage ("OnPauseGame", SendMessageOptions.DontRequireReceiver);
}
And to resume call OnResumeGame on all objects.
A basic script with movement in the Update() could have something like this:
protected bool paused;
void OnPauseGame ()
{
paused = true;
}
void OnResumeGame ()
{
paused = false;
}
void Update ()
{
if (!paused) {
// do movement
}
}
A big benefit of doing it like this is that you can implement object specific pausing and resuming functionality, like storing and restoring information for objects that use physics.
If you set Time.timeScale to 0, yet you still want to do some processing (say, for animating pause menus), remember that Time.realtimeSinceStartup is not affected by Time.timeScale. You could effectively set up your own "deltaTime" in your animated menus by subtracting the previous recorded Time.realtimeSinceStartup from the current one.