[Unity] 制限時間の設定に使えるシンプルなタイマーを実装する
今回は制限時間などに使えるタイマーを実装してみましたので実装方法を紹介します。
実装方法
まず、Hierarchy ビューからタイマーを表示する Text を追加します。
次に時間をカウントダウンさせる script を以下のように実装します。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TimerManager : MonoBehaviour { [SerializeField] private float _time; private Text _timerText; private void Start() { _timerText = gameObject.GetComponent<Text>(); _timerText.text = _time.ToString(); } void Update() { _time -= Time.deltaTime; int seconds = (int)_time; _timerText.text = seconds.ToString(); } }
_time 変数に制限時間を設定し、開始時に制限時間が描画されるようにします。
そして、Update 関数内で Time.deltaTime でフレームごとに制限時間を減算します。 減算した時間は float 型なので int 型にキャストしてテキストとして描画します。
以上がタイマーの実装方法です。