简体   繁体   English

Unity C脚本中的倒数计时器

[英]Countdown timer in Unity C script

I have been working on a Unity project for sometime, I have a timer which currently counts down from around 30 minutes, however I want this to be 4 hours counting down. 我已经在Unity项目上工作了一段时间,我有一个计时器,目前从30分钟开始倒计时,但是我希望这是4小时倒计时。 here is my code: 这是我的代码:

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

So you can see I have seconds and minutes in there, I tried to change the / 60 after minutes to 19 and when it ran it displayed 240 minutes which was fine, but the countdown seems to be very odd, minutes go down after around 20 seconds so I know thats not the right way to do it! 因此,您可以看到我在那里有秒和分钟,我尝试将/分钟后的/ 60更改为19,当它运行时显示240分钟,这很好,但是倒计时似乎很奇怪,大约20分钟后分钟就减少了秒,所以我知道那不是正确的方法!

Can anyone explain to me how to add in hours or how I can make the minutes count down from 240 minutes? 谁能向我解释如何增加小时数或如何使分钟数从240分钟开始递减?

Many thanks! 非常感谢!

Untested code below: 未经测试的代码如下:

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

I'm not sure about the construction of the remainingTime string. 我不确定剩余时间字符串的构造。 I would have used something like this: 我会用这样的东西:

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

EDIT: (gameTimer - Time.timeSinceLevelLoad)/60 is an integer operation, that's why it did not work. 编辑: (gameTimer - Time.timeSinceLevelLoad)/60是一个整数运算,这就是为什么它不起作用。 By forcing float operation it should work. 通过强制浮动操作,它应该可以工作。

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

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