Unity | ミリ秒単位で時間計測を行うスクリプト

System.TimeSpanによるDateTimeの差を表示するサンプルスクリプトです。

スポンサーリンク

サンプルスクリプト

using System;
using UnityEngine;
using TMPro;
namespace BlueBreath.Timer
{
    public class Timer : MonoBehaviour
    {
        [SerializeField]GameObject timeObj;
        TextMeshProUGUI timeText;
        [SerializeField]GameObject startButton;
        TextMeshProUGUI startText;
        DateTime dateTime = new DateTime();
        TimeSpan timeSpan = new TimeSpan(0,0,0,0,0);
        TimeSpan totalTimeSpan = new TimeSpan(0,0,0,0,0);
        TimeSpan showTimeSpan = new TimeSpan(0,0,0,0,0);
        bool timerIsActive = false;
        void Start(){
            if (!timeObj.TryGetComponent(out timeText))this.enabled = false;
            if (!startButton.TryGetComponent(out startText))this.enabled = false;
        }
        void Update() => TimerUpDate();
        public void TimerStart(){
            if(!timerIsActive){
                dateTime = DateTime.Now;
                timerIsActive = true;
                startText.SetText("Stop");
                return;
            }else{
                totalTimeSpan += timeSpan;
                timerIsActive = false;
                startText.SetText("Start");
            }
        }
        public void TimerUpDate(){
            if(!timerIsActive)return;
            //経過時間
            timeSpan = DateTime.Now - dateTime;
            TimerTMP();
        }
        public void TimerStop(){
            if(timerIsActive){
                totalTimeSpan += timeSpan;
                timerIsActive = false;
            }
        }
        public void TimerReset(){
            dateTime = DateTime.Now;
            timeSpan = new TimeSpan(0,0,0,0,0);
            totalTimeSpan = new TimeSpan(0,0,0,0,0);
            TimerTMP();
        }
        public void TimerTMP(){
            showTimeSpan = totalTimeSpan + timeSpan;
            //TMP更新
            timeText.SetText(
                "{0:00}:{1:00}:{2:000}",
                showTimeSpan.Minutes,
                showTimeSpan.Seconds,
                showTimeSpan.Milliseconds
                );
        }
    }
}

説明

ミリ秒単位の経過時間

//Int型の日、時、分、秒、ミリ秒が入ります
TimeSpan timeSpan = new TimeSpan(0,0,0,0,0);
//現在の時間から、開始時間を引く事で正確な経過時間を求めます
timeSpan = DateTime.Now - dateTime;

TextMeshProの数値を0で埋める

            timeText.SetText(
                "{0:00}:{1:00}:{2:000}",
                showTimeSpan.Minutes,
                showTimeSpan.Seconds,
                showTimeSpan.Milliseconds
                );

0で埋める書式指定子を使用して、時間を表示します。

参考:書式を指定して数値を文字列に変換する

使用例

時間計測を行うWebGL記事です。

関連・参考

関連

TextMeshProをスクリプトから操作する記事です。

参考

コメント

タイトルとURLをコピーしました