ぶろぐめんどくさい

技術系の記事と漫画レビューが入り混じった混沌

UnityでC#でniceTimeなタイマーの作り方

00:00.000などの形式で時間を表示するUIの作り方。 この記事では経過秒を取得し、例えば72.130秒から1分12秒130ミリ秒を抽出、そして01:12.130といった表示に加工することを目指します。

ここ(making a timer (00:00) minutes and seconds - Unity Answers)によい参考資料がありました。

Unityにおける時間の更新は例えばtimer += Time.deltaTimeを使います。 ちなみにTime.deltaTimeは前フレームからの経過をfloatで返します。

00:00.000などの表示は、timerの中身をあるフォーマットに従いstringに変換することで実現できます。

上記のサイトに答えがありますが、ベストアンサーな回答よりもniceTimeなスクリプトを使うほうがかっこいい気がしますので、これを参考に以下のスクリプトを書きました。

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

public class ScoreManager : MonoBehaviour {

    Text timeText;
    float timer;

    void Start () {
        timeText = this.GetComponent<Text>();
        timer = 0;
    }
    
    // Update is called once per frame
    void Update () {
        time += Time.deltaTime;
 
        int minutes = Mathf.FloorToInt(timer / 60F);
        int seconds = Mathf.FloorToInt(timer - minutes * 60);
        int mseconds = Mathf.FloorToInt((timer - minutes * 60 - seconds) * 1000);
        string niceTime = string.Format("{0:00}:{1:00}.{2:000}", minutes, seconds, mseconds);
        
        timeText.text = niceTime;
    }
}

このスクリプトをTextコンポーネントをもつUIオブジェクトに貼り付ければ時間を更新して期待通りの表示をしてくれます。 この中ではstring.Formatが神がかった動きをしてくれています。{}内の形式で数値を文字列型に加工してくれているようです。 すっごーい!  つまり分表示ならフォーマットを"{0:00}分{1:00}秒"にすればいいのです。 やっぱりすっごーい!

以上です。