【问题标题】:How to make a countdown timer with a slider如何使用滑块制作倒数计时器
【发布时间】:2018-04-08 20:32:46
【问题描述】:

在我的游戏中,我有一个表示剩余时间的滑块,剩余时间每秒减少 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;
        }
    }
}

【问题讨论】:

  • 我们需要一个比“不起作用”更精确的问题描述。
  • @Christopher 好的,我更改了描述
  • @Christopher 你会帮我写代码吗
  • @ModusTollens - 我已经部分修复了它。 OP 现在应该编辑答案并单独发布。
  • @JonBergeron 您能否复制并剪切问题中的答案并将其粘贴到答案部分?如果您愿意,您甚至可以接受自己的答案。

标签: c# user-interface unity3d timer


【解决方案1】:

你没有完全理解协程和 yield return 的工作原理。

用简单的话来说,协程总是在 yield return 时离开,允许开始下一帧,但让我们说记住它离开的地方。在下一帧中,它将在它离开的地方继续。

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

  1. 协程必须由StartCoroutine() 调用。所以代替你的线

    yield return Countdown();
    

    你必须使用

    StartCoroutine(Countdown());
    
  2. 正如之前所说的,协程在它离开的地方继续,所以你可以使用一个while循环来代替if else和一种递归调用:

    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;
        }
    }
    

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2012-04-19
    相关资源
    最近更新 更多