転職を繰り返したサラリーマンの多趣味ブログ

30才未経験でSEに転職した人の多趣味ブログ

【Unity】秒数をカウントし、UIに表示する方法

1.GameObjectを作成し、以下のスクリプトをアタッチする

const int RecoSeconds = 10;

// Textオブジェクト
public Text time;

private int seconds = 0;
	
// Update is called once per frame
void Update () {

    // UI
    time.text = "TIME:" + seconds;

    // secondsが0秒のときにカウントスタート
    if(seconds == 0)
    {
        // コルーチンのスタート
        StartCoroutine(CountTime());

    }

}

IEnumerator CountTime()
{
    
    seconds = RecoSeconds;

    while(seconds > 0)
    {
        // 1秒待機
        yield return new WaitForSeconds(1.0f);
        seconds--;
    }

}