50 lines
1.1 KiB
C#
50 lines
1.1 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
|
||
|
||
public class Timer
|
||
{
|
||
public static Timer Instance { get; private set; }
|
||
|
||
private List<TimerTask> tasks = new List<TimerTask>(); // 存储所有定时任务
|
||
|
||
private class TimerTask
|
||
{
|
||
public object target; // 目标对象 A
|
||
public Action method; // 方法 B
|
||
public float executeTime; // 任务执行时间(Time.time + C 毫秒)
|
||
}
|
||
|
||
public Timer()
|
||
{
|
||
Instance = this;
|
||
}
|
||
|
||
// 注册定时任务
|
||
public void TimerRegister(object A, Action B, float C)
|
||
{
|
||
tasks.Add(new TimerTask
|
||
{
|
||
target = A,
|
||
method = B,
|
||
executeTime = Time.time + C
|
||
});
|
||
}
|
||
|
||
public void Update()
|
||
{
|
||
if (tasks.Count == 0) return;
|
||
|
||
float currentTime = Time.time;
|
||
for (int i = tasks.Count - 1; i >= 0; i--)
|
||
{
|
||
if (currentTime >= tasks[i].executeTime)
|
||
{
|
||
tasks[i].method?.Invoke(); // 执行方法 B
|
||
tasks.RemoveAt(i); // 执行完毕后移除
|
||
}
|
||
}
|
||
}
|
||
}
|