using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class WaitTimeManager
{
private static TaskBehaviour m_Task;
static WaitTimeManager()
{
GameObject go = new GameObject("#WaitTimeManager#");
GameObject.DontDestroyOnLoad(go);
m_Task = go.AddComponent<TaskBehaviour>();
}
static public Coroutine WaitTime(float time, UnityAction callback)
{
return m_Task.StartCoroutine(Coroutine(time, callback));
}
static public void CencelWait(ref Coroutine coroutine)
{
if (coroutine != null)
{
m_Task.StopCoroutine(coroutine);
coroutine = null;
}
}
static IEnumerator Coroutine(float time, UnityAction callback)
{
yield return new WaitForSeconds(time);
if (callback != null)
{
callback();
}
}
public class TaskBehaviour : MonoBehaviour { }
}
你也可以写成单例那样,不过概念都是一样的,就是为了保证每次使用TaskBehaviour它时,都是同一个它,这样才保证了计时器的正确性。举个例子:你想要定个闹钟,然后拿起手机定了个早上8点的闹钟,过来会你想了想8点有点早改成8:10分的吧,那么此时你还是要用刚刚定闹钟的那个手机,而不是随便找个手机就可以。
为了保证内存中只有这一个TaskBehaviour
协程和构造函数毛关系。。你这问题问的。通常用静态构造函数为了类只能实例化一次,这一次通常也只在类的内部实例化出来,也就是单例,这代码结构有点混乱