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

如何修改Unity游戏计时器为分:秒格式并保留秒数两位小数?

解决Unity计时器分:秒格式显示问题

以下是修改后的完整脚本,可实现分:秒格式显示且秒数保留两位小数的功能:

using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
    [SerializeField] private TMP_Text timerText;
    float timer;

    void Start()
    {
        timerText = GetComponent<TMP_Text>();
        timer = 0.0f;
    }

    void Update()
    {
        timer += Time.deltaTime;
        // 计算整数分钟数:总时间除以60后取整
        int minutes = Mathf.FloorToInt(timer / 60);
        // 计算剩余秒数:总时间取模60
        float seconds = timer % 60;

        // 格式化输出分:秒,秒数固定保留两位小数
        timerText.text = $"Timer: {minutes:00}:{seconds:00.00}";
    }
}

关键修改说明:

  • 分钟数计算:使用Mathf.FloorToInt(timer / 60)获取总时间的整数分钟部分,避免出现小数分钟。
  • 字符串格式化:通过C#字符串插值语法,{minutes:00}确保分钟数显示为两位(如1分钟显示为01),{seconds:00.00}强制秒数显示为两位整数加两位小数,自动完成四舍五入。
  • 若不需要分钟数强制两位(如1分钟显示为1而非01),可将{minutes:00}改为{minutes}。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:15:05