How do I pause my game?

本文介绍了在Unity中实现游戏暂停的方法。可以通过设置Time.timeScale为0来暂停游戏,也可以通过实现特定的OnPauseGame和OnResumeGame函数来控制游戏对象的行为。此外,文章还提到了如何在暂停时继续处理某些进程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问:

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.



答3:

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值