Unity2Dで「カウントダウンのタイマー」を実装していきます。いくつか方法がありますが簡単な方法で作成してみます。
はじめに
Unityのバージョンは2021.3.14f1です。
下記のようなシンプルな形のタイマーを実装していきます。

分かりやすいようにサイズを大きく作成しています。
実装開始
まずは横バーのタイマーを作成してから円形のタイマーを作成していきます。
UI作成
Hierarchyで右クリックして「UI」→「Image」を追加。

名前を「Timer」にしてSourceImageをSquareに、幅と高さ(WidthとHeight)を変更して下記の様にします。

「Timer」配下に「UI」→「Image」を追加。

名前を「Fill」にして色を変更、幅と高さを調整します。

「Image Type」をFilledにして、FillAmountの数字を減らすとバーが減少している風になります。

以前作成したライフバーと同じような動きですね。
テキストの追加
残り時間を表示するテキストを追加します。「Timer」の配下に「UI」→「Text-TextMeshPro」を追加。

名前をTimerTextに変更して、FontSizeを調整します。

スクリプト作成
下記スクリプトを作成します。CountTimeは始まりの秒数、Update内で経過時間を引いて残り秒数を算出しています。
using UnityEngine; using UnityEngine.UI; using TMPro; public class Timer : MonoBehaviour { [SerializeField] private Image uiFill; [SerializeField] private TextMeshProUGUI uiText; [SerializeField] private float CountTime; private void Update() { float timer = CountTime - Time.time; int minutes = Mathf.FloorToInt(timer / 60); int seconds = Mathf.FloorToInt(timer % 60); uiFill.fillAmount = Mathf.InverseLerp(0, CountTime, timer); uiText.text = minutes.ToString("00") + ":" + seconds.ToString("00"); } }
Timerにアタッチしてパラメータをセット。

実行すると下記の様な感じのバー式のタイマーになります。

円時計式のタイマー
画像を入れ替えて時計式のタイマーにしていきます。SourceImageにCircleをセット。

imageTypeの「Fill Method」と「Fill Origin」を変更して時計回りに減少するようにセットして完成です。
