如何使用滑块制作倒数计时器

时间:2018-04-08 20:32:47

标签: c# user-interface unity3d timer

在我的游戏中,我有一个滑块代表剩余的时间,剩下的时间每秒减少1这是我想出的但是滑块除了第一次没有下降有人可以帮我修复我的代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour
{
    public float time = 100;
    public float totalTime = 100;
    public float duration = 1;

    public Slider slider;

    // Use this for initialization
    void Start()
    {
        time = totalTime;
        slider.value = time;
        StartCoroutine(CountDown());
    }

    // Update is called once per frame
    IEnumerator CountDown()
    {
        if (time > 0)
        {
            yield return new WaitForSeconds(duration);
            time -= 1;
            slider.value = time;
            yield return CountDown();
        }
    }
}

解决:

public class Timer : MonoBehaviour
{
    public float timeLeft;
    public float maxTime = 100f;
    public float duration = 1;

    public Slider slider;

    // Use this for initialization
    private void Start()
    {
        timeLeft = maxTime;
        slider.value = timeLeft;
    }

    // Update is called once per frame
    void Update()
    {
        if (timeLeft > 0)
        {
            timeLeft -= Time.deltaTime;
            slider.value = timeLeft / maxTime;
        }
        else
        {
            Time.timeScale = 0;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你并不完全了解协同程序和收益率如何恢复工作。

简单来说,协同程序总是离开收益率返回,允许下一帧开始,但让我们说记住它离开的地方。在下一帧中,它将在它离开的位置继续。

因此,如果你想使用协同程序,而不是简单地在update中使用协同程序,就像你已经建议的那样,例如这两个选项:

  1. 协程必须由StartCoroutine()调用。所以而不是你的行

    yield return Countdown();
    

    你必须使用

    StartCoroutine(Countdown());
    
  2. 如前所述,协程继续在它离开的位置,而不是if else和一种递归调用,你可以使用while循环:

    IEnumerator Countdown()
    {
        while(time > 0)
        {
            yield return new WaitForSeconds(duration);
            time -= duration;
            slider.value = time;
    
            // This leaves the coroutine at this point
            // so in the next frame the while loop continues
            yield return null;
        }
    }