You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity计时器两位毫秒格式修改求助:修改格式字符串后未生效

Unity计时器毫秒显示从三位改两位的解决方法

你遇到的问题核心是:毫秒变量的取值范围还是0-999的三位数值,仅仅修改格式字符串{2:00}无法缩短显示长度——因为00格式符仅保证输出至少两位,当数值≥100时仍会显示完整的三位。

解决步骤:

  1. 调整毫秒的计算逻辑,将原来的*1000改为*100,把取值范围压缩到0-99(对应两位毫秒)
  2. 将毫秒变量的类型从float改为int,避免浮点精度问题

修改后的完整代码:

public class Timer : MonoBehaviour
{
    public float timeValue = 0;
    public TextMeshProUGUI TimeText;

    private void Update()
    {
        timeValue += Time.deltaTime;
        DisplayTime(timeValue);
    }

    private void DisplayTime(float timeToDisplay)
    {
        int Minutes = Mathf.FloorToInt(timeToDisplay / 60);
        int Seconds = Mathf.FloorToInt(timeToDisplay % 60);
        // 计算两位毫秒:取小数部分乘以100后取整
        int MilleSeconds = Mathf.FloorToInt((timeToDisplay % 1) * 100);

        TimeText.text = string.Format("{0:0}:{1:00}:{2:00}", Minutes, Seconds, MilleSeconds);
    }
}

补充说明:

  • 如果需要对毫秒进行四舍五入(比如456毫秒显示为46而不是45),可以把Mathf.FloorToInt换成Mathf.RoundToInt
  • 修改后,计时器会稳定显示0:00:00格式,毫秒部分始终为两位,不足时自动补0

内容的提问来源于stack exchange,提问作者Sjoerd Dijksterhuis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:45:46