繁体   English   中英

Unity C脚本中的倒数计时器

[英]Countdown timer in Unity C script

我已经在Unity项目上工作了一段时间,我有一个计时器,目前从30分钟开始倒计时,但是我希望这是4小时倒计时。 这是我的代码:

seconds = Mathf.CeilToInt (gameTimer - Time.timeSinceLevelLoad) % 60;
        minutes = Mathf.CeilToInt (gameTimer - Time.timeSinceLevelLoad) / 60; 
    }

    if (seconds == 0 && minutes == 0) {
        chestfree.gameObject.SetActive(true);
        checker = 2;
    }

    remainingTime = string.Format("{0:00} : {1:00}", minutes, seconds); 
    if (seconds != 0 && minutes != 0) {
        h.text = remainingTime.ToString ();
    } else {

        h.text = "Get";
    }

因此,您可以看到我在那里有秒和分钟,我尝试将/分钟后的/ 60更改为19,当它运行时显示240分钟,这很好,但是倒计时似乎很奇怪,大约20分钟后分钟就减少了秒,所以我知道那不是正确的方法!

谁能向我解释如何增加小时数或如何使分钟数从240分钟开始递减?

非常感谢!

未经测试的代码如下:

hours = Mathf.FloorToInt((float)(gameTimer - Time.timeSinceLevelLoad) / 3600);
minutes = Mathf.FloorToInt((float)(gameTimer - Time.timeSinceLevelLoad-hours*3600) / 60); 
seconds = Mathf.FloorToInt((gameTimer - Time.timeSinceLevelLoad) % 60);



if (seconds == 0 && minutes == 0 && hours == 0) {
    chestfree.gameObject.SetActive(true);
    checker = 2;
}
//remainingTime = string.Format("{0}:{1}:{2}",hours,minutes,seconds);
remainingTime = string.Format("{2:00} : {0:00} : {1:00}", minutes, seconds,hours); 
if (seconds != 0 && minutes != 0 && hours != 0) {
    h.text = remainingTime.ToString ();
} else {

    h.text = "Get";
}

我不确定剩余时间字符串的构造。 我会用这样的东西:

remainingTime = string.Format("{0}:{1}:{2}",hours,minutes,seconds);

编辑: (gameTimer - Time.timeSinceLevelLoad)/60是一个整数运算,这就是为什么它不起作用。 通过强制浮动操作,它应该可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM