如何让我的计时器达到小数点后两位?



嗨,我想知道是否有人知道如何让这个计时器只做两个小数位。目前,它最多显示 6 位小数。我正在制作一个计时器,从 0 开始上升,以查看玩家完成一门课程需要多长时间。如果你知道如何让计时器在你死后也继续,并转移到下一个场景,那将不胜感激。再次感谢。

这是我使用的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
public float timeStart = 0;
public Text textBox;
// Start is called before the first frame update
void Start()
{
PlayerPrefs.SetInt("Second", 59);
PlayerPrefs.SetInt("Minute", 9);
StartCoroutine("bekle1sn");
textBox.text = timeStart.ToString();
}
// Update is called once per frame
void Update()
{
timeStart += Time.deltaTime;
textBox.text = (timeStart).ToString("F2");
textBox.enabled = true;
textBox.text = PlayerPrefs.GetInt("Minute") + ":" + PlayerPrefs.GetInt("Second").ToString();
}
IEnumerator bekle1sn()
{
for (int iCnt = 0; iCnt < 600; iCnt++)
{
yield return new WaitForSeconds(1); //Bekleme
PlayerPrefs.SetInt("Second", PlayerPrefs.GetInt("sureSaniye") + 1);

if (PlayerPrefs.GetInt("Second") + 1 == 0)
{
PlayerPrefs.SetInt(("Second"), 0);
PlayerPrefs.SetInt("Minute", PlayerPrefs.GetInt("Minute") + 1);
if (PlayerPrefs.GetInt("Minute") + 1 == 0)
{
// finish the screen  

}
}
}
}
}

我最近在做这样一个项目。 我的从 10 分钟开始倒计时。 您可以自己编辑此代码并将其传输到下一个场景。

string fmt = "00.##";
start(){
PlayerPrefs.SetInt ("Second", 59);
  PlayerPrefs.SetInt ("Minute", 9);
StartCoroutine("bekle1sn");
}
void Update()
{
sureTextTMP.enabled = true;
sureTextTMP.text = PlayerPrefs.GetInt("Minute") + ":" + PlayerPrefs.GetInt("Second").ToString(fmt);
}


IEnumerator bekle1sn()
{
for (int iCnt = 0; iCnt < 600; iCnt++)
{
yield return new WaitForSeconds(1); //Bekleme
PlayerPrefs.SetInt("Second", PlayerPrefs.GetInt("Second") - 1);

if (PlayerPrefs.GetInt("Second") - 1 == 0)
{
PlayerPrefs.SetInt(("Second"), 59);
PlayerPrefs.SetInt("Minute", PlayerPrefs.GetInt("Minute") - 1);
if (PlayerPrefs.GetInt("Minute") - 1 == 0)
{
// finish the screen  

}
}
}
}

您可以使用 String 类的格式化功能,如下所示:

textBox.text = (timeStart).ToString("F2");

这会将其四舍五入到您需要的小数点后 2 位。

textBox.text = (timeStart).ToString("F0");

这会将其四舍五入为整数

使用标准数字格式字符串:

float f = 12.4435345f;
f.ToString("F2"); // 12.44

最新更新