簡體   English   中英

C# 試圖創建一個計時器。 它似乎不起作用

[英]C# Trying to create a timer. It doesn't seem to work

public class TimerCountdown : MonoBehaviour
{
    float currentTime = 0f;
    float startingTime = 70f;
    float hours = 0;
    float minutes = 0;
    float seconds = 0;

    [SerializeField] Text countdownText;

    void Start()
    {
        currentTime = startingTime;
        float hours = currentTime / 3600 ;
        float minutes = currentTime % 3600 / 60 ;
        float seconds = currentTime % 60 ;
    }

    void Update()
    {
        currentTime -=1 * Time.deltaTime;
        hours = currentTime / 3600 ;
        minutes = currentTime % 3600 / 60 ;
        seconds = currentTime % 60 ;
        countdownText.text = hours.ToString("00") + ":" + minutes.ToString("00") + ":" + seconds.ToString("00") + " --- " + currentTime.ToString("0");
    }
}

所以這是我的功能。 當我統一運行它時,倒計時有效,但轉換為分鍾似乎是錯誤的。 比如,當它變低時,分鍾不會每 2 分鍾改變一次(180 秒過去了)。 這是為什么? 我究竟做錯了什么? 此外,如果我將其增加 9000f(2 小時 30 分鍾),它也會這樣做,即使它是 59 秒,它仍然保持 30,而不是 29。有幫助嗎? 我的邏輯有什么錯誤嗎?

發生的情況是,當您將浮點數轉換為字符串時,浮點數變得四舍五入。

如果您采用 1 分 33 秒 = 93f 之類的簡單方法並運行您的函數,您將得到:

float floatTime = 93f;
var floatMinutes = floatTime / 60; // floatMinutes = 1.55
Console.WriteLine(floatMinutes.ToString("00")); // Outputs: 02

但是,如果您使用整數數學,則余數將被丟棄:

int intTime = 93;
var intMinutes = intTime / 60; // intMinutes = 1
Console.WriteLine(intMinutes.ToString("00")); // Outputs: 01

要使浮動顯示屬性:

public void Update()
{
    currentTime -= 1 * Time.deltaTime;
    hours = (float)Math.Floor(currentTime / 3600);
    minutes = (float)Math.Floor(currentTime % 3600 / 60);
    seconds = currentTime % 60;
    CountdownText = hours.ToString("00") + ":" + minutes.ToString("00") + ":" + seconds.ToString("00") + " --- " + currentTime.ToString("0");
}

分鍾不會每 2 分鍾改變一次(180 秒過去了)。 這是為什么?

您發布的代碼中沒有任何內容可以表明分鍾值一次卡住兩分鍾的原因(或三...180 秒是三分鍾,而不是兩分鍾,因此您的意思不是很清楚)。

此答案的作者表明您的描述完全錯誤,並且分鍾值的更改之間沒有兩分鍾的延遲。 他們的假設可能正確,也可能不正確; 鑒於問題的措辭,很難說。

也就是說,在我看來,你的整個方法無論如何都是錯誤的。 考慮到 .NET 對處理內置時間值有很好的支持,做所有這些數學計算是沒有意義的。 我會將您的代碼更改為如下所示:

public class TimerCountdown : MonoBehaviour
{
    float currentTime = 0f;
    const float startingTime = 70f;

    [SerializeField] Text countdownText;

    void Start()
    {
        currentTime = startingTime;
    }

    void Update()
    {
        currentTime -= Time.deltaTime;
        countdownText.text = $"{TimeSpan.FromSeconds(currentTime):hh\\:mm\\:ss}" + " --- " + currentTime.ToString("0");
    }
}

上面還使用字符串插值進行字符串格式化。 這在您使用的 Unity3d 版本中可能可用,也可能不可用。 如果沒有,您可以使用舊的ToString()方法:

countdownText.text = TimeSpan.FromSeconds(currentTime).ToString("hh\\:mm\\:ss") + " --- " + currentTime.ToString("0");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM