简体   繁体   中英

C# Time Management (with Unity 2D)

I ran into a little issue whilst using C#/Unity in combination with a litte countdown timer. The countdown is working fine an as expected, as long as the number of total timeToDisplay is not too big (eg more than a day)

r/Unity2D - Asking for Help: Countdown strangely stops when there is too much remaining time As you can see, the user has the possibility to add time to that countdown, which (again) works fine, until it's too much.

Using TextMeshPro and TextMeshPro-Buttons.

Image of Countdown + Buttons to add Seconds/Minutes/Hours/Days

However... here's the code:

using UnityEngine;
using TMPro;


public class Controller : MonoBehaviour
{
    public float timeValue = 78000;
    public TMP_Text timerText;

    // I also tried FixedUpdate, but error still occured
    void Update()
    {
        if (timeValue > 0)
        {
            timeValue -= Time.deltaTime;
        }
        else
        {
            timeValue = 0;
        }

        DisplayTime(timeValue);
    }

    void DisplayTime(float timeToDisplay)
    {
        float days = Mathf.FloorToInt(timeToDisplay / 86400);
        timeToDisplay = timeToDisplay % 86400;

        float hours = Mathf.FloorToInt(timeToDisplay / 3600);
        timeToDisplay = timeToDisplay % 3600;

        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        timeToDisplay = timeToDisplay % 60;

        float seconds = Mathf.FloorToInt(timeToDisplay);
        if (seconds < 0)
        {
            seconds = 0;
        }

        timerText.text = string.Format("{0:00} days {1:00} hours {2:00} minutes {3:00} seconds", days, hours, minutes, seconds);

    }
   
    public void AddDay()
    {
        /* 86400 seconds/day */
        timeValue += 86400;
    }

    public void AddHour()
    {
        /* 3600 seconds/hour */
        timeValue += 3600;
    }

    public void AddMinute()
    {
        timeValue += 60;
    }

    public void AddSecond()
    {
        timeValue += 1;
    }
}

Does anybody know what I'm missing here?

problem on here: timeValue -= Time.deltaTime , float have a little deviation

public float timeValue = 78000;
float beginTime = 0;
void Start()
{
    beginTime = Time.time;
}
// I also tried FixedUpdate, but error still occured
void Update()
{
    float usedTime = Time.time - beginTime;
    if( timeValue - usedTime > 0 )
    {
        DisplayTime(timeValue - usedTime);
    }
    else
    {  
        DisplayTime(0); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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