以下這段程式碼可以用來在畫面上添加一個不斷顯示已經過秒數的計時器,假設你的文字物件叫做TextTimeCounter,請先把它放在畫面上你想要的地方,並且把它拖曳至這個程式碼的物件欄位中,就可以正常運作了。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Counter : MonoBehaviour
{
public Text TimeCounter;
// Start is called before the first frame update
void Start()
{
StartCoroutine(MyCounter());
}
IEnumerator MyCounter()
{
while(true)
{
int current = int.Parse(TimeCounter.text);
current++;
TimeCounter.text = current.ToString();
yield return new WaitForSeconds(1f);
}
}
}