第一種方式是利用Unity中的協程,代碼如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DemoTest : MonoBehaviour { public Text text; //測試用的數字 public int MyTime = 60; void Start () { //開啟協程 StartCoroutine (StartUpdate ()); } //一秒鍾減去1 IEnumerator StartUpdate () { while (true) { if (MyTime > 0) { MyTime -= 1; text.text = UpdateTime (MyTime); } else { break; } yield return new WaitForSeconds (1f); } } /// <summary> /// 時間換算 /// </summary> /// <returns>The time.</returns> /// <param name="inputTime">輸入的時間</param> string UpdateTime (int inputTime) { string temp; int minute, seconds; minute = (int)(inputTime / 60); Debug.Log ("minute = " + minute); seconds = inputTime % 60; Debug.Log ("seconds = " + seconds); // 這樣的話,當minute<0的時候只有一個數字,可能有的需求上不允許,所以就換一種方式 // if (seconds >= 10) { // temp = "0" + minute + ":" + seconds; // } else { // temp = minute + ":" + seconds; // } //優化版,利用三目運算符進行取值,這樣更好的實現倒計時 string minTemp = (minute < 10) ? "0" + minute : minute.ToString (); string secTemp = (seconds < 10) ? "0" + seconds : seconds.ToString (); temp = minTemp + ":" + secTemp; return temp; } }
第二種方式,利用Update,原理是一樣的
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DemoTest : MonoBehaviour { public Text text; //測試用的數字 public int MyTime = 60; float timer = 0; float timerInterval = 1f; void Update () { timer += Time.deltaTime; if (timer >= timerInterval) { timer = 0; MyTime -= (int)timerInterval; if (MyTime < 0) { return; } text.text = UpdateTime (MyTime); } } /// <summary> /// 時間換算 /// </summary> /// <returns>The time.</returns> /// <param name="inputTime">輸入的時間</param> string UpdateTime (int inputTime) { string temp; int minute, seconds; minute = (int)(inputTime / 60); Debug.Log ("minute = " + minute); seconds = inputTime % 60; Debug.Log ("seconds = " + seconds); // 這樣的話,當minute<0的時候只有一個數字,可能有的需求上不允許,所以就換一種方式 // if (seconds >= 10) { // temp = "0" + minute + ":" + seconds; // } else { // temp = minute + ":" + seconds; // } //優化版,利用三目運算符進行取值,這樣更好的實現倒計時 string minTemp = (minute < 10) ? "0" + minute : minute.ToString (); string secTemp = (seconds < 10) ? "0" + seconds : seconds.ToString (); temp = minTemp + ":" + secTemp; return temp; } }
