67 lines
1.7 KiB
C#
67 lines
1.7 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace WZ
|
|
{
|
|
public class TimerUtils : MonoBehaviour
|
|
{
|
|
private static TimerUtils _instance;
|
|
|
|
public static void Initialize()
|
|
{
|
|
if (_instance != null) return;
|
|
GameObject timerObject = new GameObject("TimerUtils");
|
|
timerObject.hideFlags = HideFlags.HideInHierarchy;
|
|
DontDestroyOnLoad(timerObject);
|
|
_instance = timerObject.AddComponent<TimerUtils>();
|
|
}
|
|
|
|
public static void DelayExecute(float delay, System.Action action)
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
Debug.LogWarning("TimerUtils not initialized. Call TimerUtils.Initialize() first.");
|
|
return;
|
|
}
|
|
|
|
_instance.StartCoroutine(DelayExecuteCoroutine(delay, action));
|
|
}
|
|
|
|
public static void StopAllDelayedActions()
|
|
{
|
|
if (_instance != null)
|
|
{
|
|
_instance.StopAllCoroutines();
|
|
}
|
|
}
|
|
|
|
public static void Dispose()
|
|
{
|
|
if (_instance != null)
|
|
{
|
|
Destroy(_instance.gameObject);
|
|
_instance = null;
|
|
}
|
|
}
|
|
|
|
private static IEnumerator DelayExecuteCoroutine(float delay, System.Action action)
|
|
{
|
|
yield return new WaitForSeconds(delay);
|
|
action?.Invoke();
|
|
}
|
|
|
|
void OnDestroy()
|
|
{
|
|
// 清理静态引用,防止内存泄漏
|
|
if (_instance == this)
|
|
{
|
|
_instance = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|