112 lines
2.7 KiB
C#
112 lines
2.7 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
|
|
namespace GuruClient
|
|
{
|
|
public class Timer
|
|
{
|
|
private static Timer _instance;
|
|
|
|
public static Timer Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = new Timer();
|
|
}
|
|
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
int id = 0;
|
|
Dictionary<int, Coroutine> timerMap = new Dictionary<int, Coroutine>();
|
|
public int SetTimeout(float sec, Action complete)
|
|
{
|
|
id++;
|
|
Coroutine coroutine = Coroutiner.Start(TimeoutCallback(sec, complete));
|
|
timerMap[id] = coroutine;
|
|
return id;
|
|
}
|
|
|
|
public int WaitFrame(Action complete)
|
|
{
|
|
id++;
|
|
Coroutine coroutine = Coroutiner.Start(WaitFrameInner(complete));
|
|
timerMap[id] = coroutine;
|
|
return id;
|
|
}
|
|
|
|
public void SetTimeoutAsync(float sec, Action callback)
|
|
{
|
|
int timerID = SetTimeout(sec, delegate
|
|
{
|
|
callback?.Invoke();
|
|
});
|
|
|
|
void CancelAction()
|
|
{
|
|
Stop(timerID);
|
|
}
|
|
}
|
|
|
|
IEnumerator WaitFrameInner(Action complete)
|
|
{
|
|
yield return null;
|
|
complete?.Invoke();
|
|
}
|
|
|
|
IEnumerator TimeoutCallback(float sec, Action complete)
|
|
{
|
|
yield return new WaitForSeconds(sec);
|
|
complete?.Invoke();
|
|
}
|
|
|
|
|
|
public int SetInterval(float sec, Action complete)
|
|
{
|
|
id++;
|
|
Coroutine coroutine = Coroutiner.Start(IntervalCallback(sec, complete));
|
|
timerMap[id] = coroutine;
|
|
return id;
|
|
}
|
|
|
|
public int SetInterval(WaitForSeconds wfs, Action complete)
|
|
{
|
|
id++;
|
|
Coroutine coroutine = Coroutiner.Start(IntervalCallback(wfs, complete));
|
|
timerMap[id] = coroutine;
|
|
return id;
|
|
}
|
|
|
|
IEnumerator IntervalCallback(float sec, Action complete)
|
|
{
|
|
while (true)
|
|
{
|
|
yield return new WaitForSeconds(sec);
|
|
complete?.Invoke();
|
|
}
|
|
}
|
|
|
|
IEnumerator IntervalCallback(WaitForSeconds wfs, Action complete)
|
|
{
|
|
while (true)
|
|
{
|
|
yield return wfs;
|
|
complete?.Invoke();
|
|
}
|
|
}
|
|
|
|
public void Stop(int id)
|
|
{
|
|
if (timerMap.TryGetValue(id, out var coroutine))
|
|
{
|
|
Coroutiner.Instance.StopCoroutine(coroutine);
|
|
}
|
|
}
|
|
}
|
|
} |