Unity 计时器工具类

一个项目中可能要使用多个计时器,为了应对这种情况,写了一个计时器管理器

单例

public class Singleton<T> where T : new()
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
            }
            return _instance;
        }
    }
}

计时器类

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

public class Timer
{
    string name;
    public Timer(string name)
    {
        this.name = name;
    }

    bool isRecording = false;
    float startTime;

    public void StartRecording()
    {
        isRecording = true;
        startTime = Time.time;
    }

    public float GetCurrentRecord()
    {
        if (isRecording)
        {
            float deltaTime = Time.time - startTime;
            return deltaTime;
        }
        else return 0;
    }

    public void Reset()
    {
        isRecording = false;
        startTime = 0;
    }
}

计时器管理器类

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

public class TimerManager : Singleton<TimerManager>
{
    Dictionary<string, Timer> dict = new Dictionary<string, Timer>();

    void CreateTimer(string timerName)
    {
        Timer timer = new Timer(timerName);
        dict.Add(timerName, timer);
    }

    public Timer GetTimer(string timerName)
    {
        if (!dict.ContainsKey(timerName))
            CreateTimer(timerName);
        return dict[timerName];
    }
}

使用方法

Timer timer;
void Awake()
{
    timer = TimerManager.Instance.GetTimer("Arrow");
}

timer.StartRecording();
timer.GetCurrentRecord();
timer.Reset();

猜你喜欢

转载自blog.csdn.net/weixin_43673589/article/details/124218153