Unity

在Unity場景中添加計時器的程式片段

以下這段程式碼可以用來在畫面上添加一個不斷顯示已經過秒數的計時器,假設你的文字物件叫做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);
        }

    }
}

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s