c# - 如何在返回 0 之前停止显示 60 秒

标签 c# unity3d

我试图在播放器的 UI 中显示时间,但我似乎无法在它返回 0 之前停止显示 60 秒。我认为它会在显示任何内容之前先执行 if 语句中的所有操作,但是似乎并非如此。这是我的代码:

private void Update() {

    seconds += timeMultiplier * Time.deltaTime;

    if (seconds >= 60) {
        seconds -= 60;
        minutes += 1;
    } else if (minutes >= 60) {
        minutes -= 60;
        hours += 1;
    } else if (hours >= 24) {
        hours -= 24;
        days += 1;
    } else if (days >= 7) {
        days -= 7;
        weeks += 1;
    } else if (weeks >= 52.17857f) {
        weeks -= 52.17857f;
        years += 1;
    }

}

public string DisplayTimeInformation() {
    StringBuilder builder = new StringBuilder();

    builder.Append(hours.ToString("#00")).Append(":").Append(minutes.ToString("#00"));

    if (displaySeconds) {
        builder.Append(":").Append(seconds.ToString("#00")).Append(" ");
    } else {
        builder.Append(" ");
    }

    return builder.ToString();
}

我尝试使用与普通 seconds 变量相同的第二个 displayedSeconds 并将其限制为 59,即使它在技术上仍然准确,但它会徘徊在 59 上稍微加速,然后从 00 加速到 01,然后恢复正常,这看起来不太好。

最佳答案

无需计算所有这些时间属性。记录某事开始的时间要容易得多:

var startedOn = DateTime.Now;

然后每次显示持续时间时:

var difference = DateTime.Now - startedOn;

这为您提供了一个可以轻松显示的漂亮的 TimeSpan 对象:

var timeInString = difference.ToString(@"hh\:mm\:ss");

参见 here了解如何指定自己的格式字符串。

关于c# - 如何在返回 0 之前停止显示 60 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59611093/

相关文章:

c# - 如果我正在更新 DataRow,我是锁定整个 DataTable 还是只锁定 DataRow?

c# - 我如何滥用空合并运算符?这是正确评估 "null"吗?

c# - Visual Studio Express 用户的数据生成计划有哪些替代方案?

c# - C# 的 TreeView /文件 View 控件

c# - Unity中命名空间 `Windows'中不存在类型或命名空间名称 `UnityEngine'

c# - 为什么实例化时 Unity Prefab 值错误?

c# - 在 Unity 中在 Sprite 上写文本

c# - 如何禁用鼠标单击时的对象控制?

c# - DropdownList.selectedIndex 始终为 0(是的,我有 !isPostBack)

c# - 在枚举列表中的按钮上使用 jquery