2025-07-17 18:26:28 +08:00

50 lines
1.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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); // 执行完毕后移除
}
}
}
}