文章目录
1.前言
unity开发过程中,经常用到一些特定的协程功能,比如延时触发、等待触发、重复操作等。unity自带Invoke以及InvokeRepeating方法,但这些方法均采用反射机制,性能消耗,而且代码混淆时极其容易出错。所以再次对这些功能做以下简单封装。方便后续使用。
2.CoroutineJobCenter
CoroutineJobCenter封装了需要的基本方法。
2.1 延时触发
延时一定时间触发。
public IEnumerator StartJobDelayed(float delayedTime, Action action)
{
yield return new WaitForSeconds(delayedTime);
if (action != null)
{
action();
}
}
public IEnumerator StartJobDelayed<T>(float delayedTime, Action<T> action, T t)
{
yield return new WaitForSeconds(delayedTime);
if (action != null)
{
action(t);
}
}
2.2 等待触发
等待某一条件返回true时触发,采用unity自带的WaitUntil类。
public IEnumerator StartJobUntil(Func<bool> funtion, Action action)
{
yield return new WaitUntil(funtion);
if (action != null)
{
action();
}
}
public IEnumerator StartJobUntil<T>(Func<bool> funtion, Action<T> action, T t)
{
yield return new WaitUntil(funtion);
if (action != null)
{
action(t);
}
}