【发布时间】:2020-06-12 02:54:54
【问题描述】:
我正在用 C# 为游戏创建计时器:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // key to ensuring this works. interfaces with the ui.
public class Timer2 : MonoBehaviour
{
public static float TimerValue = 120; // initial timer value
Text timer;
// Use this for initialization
void Start()
{
timer = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
timer.text = ": " + TimerValue;
TimerValue = TimerValue - Time.deltaTime;
}
}
这个计时器解决方案的问题在于它将计时器显示为浮点数(见下图)。虽然从技术上讲,它看起来真的很糟糕,并且数字左右移动(由于数字的宽度不同)使其难以阅读。
如何四舍五入这个数字,使其显示为整数?我环顾四周,只发现双精度和十进制数据类型的舍入。我也无法弄清楚如何使用变量进行舍入,因为我尝试的所有示例都不适用于变量。理想情况下,我想继续使用 float,因为它更容易操作,而且我不需要小数 ro double 的细节。
【问题讨论】:
-
Math.Round也适用于浮点数 -
我很困惑
Mathf.Round有什么问题? -
我不确定您所说的“使用变量进行舍入”是什么意思。你永远不会对变量进行四舍五入。你舍入一个值。该值可能存储在变量中,但它不是四舍五入的变量。你能解释一下你的意思吗?