【问题标题】:Time countdown doesn't stop at 0:0.0 and it never reaches the else statement时间倒计时不会在 0:0.0 停止并且它永远不会到达 else 语句
【发布时间】:2020-09-23 22:14:46
【问题描述】:

我在到达 Update 方法中的 else 语句时遇到问题,我不知道如何让这个时钟停止。 S startTime 以秒为单位。如果你做到90.0f,你将有 1.30 分钟。问题是我需要在到达0:0.0 时停止这个时钟。

public Text TimerText;
private float startTime = 3.0f;
private bool start = false;
private float _time;
private float _minutes, _seconds;

// Use this for initialization
void Start ()
{
    start = false;
    startTime = 3.0f;
}

// Update is called once per frame
void Update ()
{
   // if (start)
  //  return;
    if (startTime > 0.0f)
    {
        _time = startTime - Time.time; // ammount of time since the time has started
        _minutes = (int)_time / 60;
        _seconds = _time % 60;
        TimerText.text = _minutes + ":" + _seconds.ToString("f1");
    }
    else
        Debug.Log("we are here"); 
}

private void CheckGameOver()
{
    Debug.Log("gameover");
}

public void StartTime()
{
    TimerText.color = Color.black;
    start = true;
}

【问题讨论】:

  • 我看不到你在哪里改变startTime

标签: c# unity3d time


【解决方案1】:

使用Time.deltaTime 代替Time.time 并更改:

if (_time> 0.0f) 
{...}

_time = startTime 添加到Start()

【讨论】:

    【解决方案2】:

    建议使用Time.deltaTime,就像 Pawel 在他的回答中所做的那样。

    我知道这个问题已经解决了,但万一你想知道为什么你的代码不工作,那是因为当你做if (startTime > 0.0f)时,你应该在if语句中递减startTime。如果你不这样做,startTime>0 将永远是true,这意味着 if 语句将永远运行。

    您仍然可以通过将 if (startTime > 0.0f) 替换为 if (Time.time < startTime) 来解决此问题。您不再需要递减,但它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      相关资源
      最近更新 更多