如何统一添加简历倒计时游戏?

时间:2017-03-20 05:31:16

标签: c# unity3d

所以我在Unity制作一个类似于任何&#34的2D应用程序;躲避掉落的物体"。我添加了暂停功能,但是我想在退出暂停菜单后添加倒数计时器。我现在所拥有的是这样的:

public void Pressed () {
    if (Time.timeScale == 0) {
        pauseMenu.SetActive(false);
        countdown.text = "3";
        yield WaitForSeconds(1);
        // repeat for 2 and 1
        Time.timeScale = currentTimeScale;
    } else {
        Time.timeScale = 0;
        pauseMenu.SetActive(true);
    }
}

关于对这个特定倒计时进行编码的正确方法的任何建议,或者如何一般地解决我的问题都会非常有帮助。 谢谢! 布兰登

1 个答案:

答案 0 :(得分:0)

已经有很多倒数计时器的实现。例如,请参阅thisthis

一般的想法是使用int字段来节省剩余时间。或者在协程中使用yield WaitForSeconds(1)来保存状态。

using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour {

    void Start() {
        StartCoroutine(CountDown());
    }

    IEnumerator CountDown() {
        countdown.text = "3";
        yield return new WaitForSeconds(1);
        countdown.text = "2";
        yield return new WaitForSeconds(1);
        countdown.text = "1";
        yield return new WaitForSeconds(1);
        //time up, now resume the app
    }
}

<强>更新

关于如何暂停应用,请参阅thisthis

  

Time.realtimeSinceStartup返回自启动以来的时间,不受Time.timeScale影响。

public static class CoroutineUtilities 
{
     public static IEnumerator WaitForRealTime(float delay){
        while(true){
            float pauseEndTime = Time.realtimeSinceStartup + delay;
            while (Time.realtimeSinceStartup < pauseEndTime){
                yield return 0;
            }
            break;
        }
    }
}

Usabilty:

 yield return StartCoroutine(CoroutineUtilities.WaitForRealTime(1));

然后我们在上面的代码中使用yield return StartCoroutine(CoroutineUtilities.WaitForRealTime(1))代替yield return new WaitForSeconds(1)

using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour {

    void Start() {
        StartCoroutine(CountDown());
    }

    IEnumerator CountDown() {
        countdown.text = "3";
        yield return StartCoroutine(CoroutineUtilities.WaitForRealTime(1));
        countdown.text = "2";
        yield return StartCoroutine(CoroutineUtilities.WaitForRealTime(1));
        countdown.text = "1";
        yield return StartCoroutine(CoroutineUtilities.WaitForRealTime(1));
        //time up, now resume the app
    }
}