[英]How do i make my timer go to two decimal places?
嗨,我想知道是否有人知道如何讓這個計時器只做兩位小數。 目前它最多顯示 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
}
}
}
}
}
使用標准數字格式字符串:
float f = 12.4435345f;
f.ToString("F2"); // 12.44
您可以像這樣使用字符串 class 的格式化功能:
textBox.text = (timeStart).ToString("F2");
這會將其四舍五入到您需要的 2 位小數。
textBox.text = (timeStart).ToString("F0");
這會將其四舍五入為整數
我最近在做這樣一個項目。 我的從 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
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.