Unity C脚本中的倒计时器

时间:2016-09-01 19:31:47

标签: c# unity3d timer

我一直在研究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分钟开始减少?

非常感谢!

1 个答案:

答案 0 :(得分:0)

以下未经测试的代码:

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字符串的构造。我会用这样的东西:

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

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

相关问题