我一直在为暂停菜单编写脚本,但我不知道如何在开始执行下一行之前使其停止这是代码,我要求这样做是因为多次执行“ if”,因为检测到我仍在按“取消”按钮。 (我使用c#并在Unity 5上工作)谢谢
using UnityEngine;
using System.Collections;
public class MenuPausa : MonoBehaviour {
public GameObject menuPausa;
private bool pausaMenu = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Cancel") || pausaMenu == false) {
menuPausa.SetActive (true);
Time.timeScale = 0;
WaitForSeconds(1);
pausaMenu = true;
} else {
menuPausa.SetActive (false);
Time.timeScale = 1;
Invoke("waiting",0.3f);
}
}
}
我会使用像这样的协程:
bool paused = false;
void Update ()
{
if (paused) // exit method if paused
return;
if (Input.GetButtonDown("PauseButton"))
StartCoroutine(OnPause()); // pause the script here
}
// Loops until cancel button pressed
// Sets pause flag
IEnumerator OnPause ()
{
paused = true;
while (paused == true) // infinite loop while paused
{
if (Input.GetButtonDown("Cancel")) // until the cancel button is pressed
{
paused = false;
}
yield return null; // continue processing on next frame, processing will resume in this loop until the "Cancel" button is pressed
}
}
这仅“暂停”并恢复该单个脚本。所有其他脚本将继续执行其Update方法。要暂停与帧速率无关的方法(即物理方法),请在暂停时将Time.timeScale = 0f设置,在不暂停时将其设置回1f。如果需要暂停所有其他脚本,并且它们取决于帧速率(即Update方法),则使用全局暂停标志代替本示例中使用的本地暂停变量,并检查是否在每个Update方法中都设置了该标志,如本例所示。
[如果我误解了,我深表歉意,但是在我看来,您好像正在使用“取消”按钮打开和关闭暂停菜单,并且由于“取消”按钮仍处于按下状态。在我看来,该脚本旨在成为要打开和关闭的菜单对象的组件。如果是这样,我建议如下:
要将此脚本用于菜单本身以外的其他对象(例如MenuManager对象或其他东西,我也会将此脚本的名称更改为MenuManger,以避免将其与实际菜单混淆),该脚本将在场景中保持活动状态。在场景中有一个PauseMenu对象,该对象已分配给此MenuManager的“ menuPausa”属性。然后,我将删除pausaMenu变量。另外,请确保将此脚本作为组件添加到仅一个对象(MenuManager)中,否则第二个对象可能会在同一帧中更新,并再次关闭菜单。
方法末尾,放置
Thread.Sleep(1000);
它将暂停执行1000毫秒== 1秒。这个简单的解决方案是否足够?或者您需要一个带有计时器的更复杂的解决方案?
您可以使用计时器,将其从工具栏中插入,更改时间间隔(以毫秒为单位,然后完成操作,请使用脚本timer.Start();
和timer.Stop();
那就是我用的。