一个项目中可能要使用多个计时器,为了应对这种情况,写了一个计时器管理器
单例
public class Singletonwhere 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{ Dictionary dict = new Dictionary (); 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();



