如何修改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
相关产品推荐
相关产品推荐

