日々是好日~every day is a good day~

日常の中の非日常の備忘録

【Unity】タイマーを表示する

タイマー表示はこれまでよく使ってきましたが まだここに残してなかったので いまさらですがやり方を
1.ヒエラルキーの+をクリックしてUI/古い機能/テキストを選択

2.位置 サイズ テキスト フォントサイズ等をお好みで調整しオブジェクトの名前をTimerTextに変更

3.プロジェクトタブ内で右クリックし作成/C#スクリプトを選択
Timerというスクリプトを作成する

4.Timerスクリプトを編集

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
    private Text timerText;
    private int minutes;
    private float seconds;
    private float lastSeconds;
    // Start is called before the first frame update
    void Start()
    {
        minutes = 0;
        seconds = 0f;
        lastSeconds = 0f;
        timerText = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        seconds += Time.deltaTime;
        if (seconds >= 60f)
        {
            minutes++;
            seconds = seconds - 60;
        }
        if ((int)seconds != (int)lastSeconds)
        {
            timerText.text = minutes.ToString("00") + ":" + ((int)seconds).ToString("00");
        }
        lastSeconds = seconds;
    }
}

5.TimerスクリプトをTimerTextにアタッチ

実行するとタイマー表示が始まります

アレンジすればカウントダウンにもなりますね
簡単ですがよく使う機能なのでスクリプトをコピペしてお使いください