using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 任务执行队列
///
public class ActionQueue : MonoBehaviour
{
event Action onComplete;
List actions = new List();
public static ActionQueue InitOneActionQueue()
{
return new GameObject().AddComponent();
}
///
/// 添加一个任务到队列
///
/// 开始时执行的方法
/// 判断该节点是否完成
///
public ActionQueue AddAction(Action startAction, Func IsCompleted)
{
actions.Add(new OneAction(startAction, IsCompleted));
return this;
}
///
/// 添加一个协程方法到队列
///
/// 一个协程
///
public ActionQueue AddAction(IEnumerator enumerator)
{
actions.Add(new OneAction(enumerator));
return this;
}
///
/// 添加一个任务到队列
///
/// 一个方法
///
public ActionQueue AddAction(Action action)
{
actions.Add(new OneAction(action));
return this;
}
///
/// 绑定执行完毕回调
///
///
///
public ActionQueue BindCallback(Action callback)
{
onComplete += callback;
return this;
}
///
/// 开始执行队列
///
///
public ActionQueue StartQueue()
{
StartCoroutine(StartQueueAsync());
return this;
}
IEnumerator StartQueueAsync()
{
if (actions.Count > 0)
{
if (actions[0].startAction != null)
{
actions[0].startAction();
}
}
while (actions.Count > 0)
{
yield return actions[0].enumerator;
actions.RemoveAt(0);
if (actions.Count > 0)
{
if (actions[0].startAction != null)
{
actions[0].startAction();
}
}
else
{
break;
}
yield return new WaitForEndOfFrame();
}
if (onComplete != null)
{
onComplete();
}
Destroy(gameObject);
}
class OneAction
{
public Action startAction;
public IEnumerator enumerator;
public OneAction(Action startAction, Func IsCompleted)
{
this.startAction = startAction;
//如果没用协程,自己创建一个协程
enumerator = new CustomEnumerator(IsCompleted);
}
public OneAction(IEnumerator enumerator, Action action = null)
{
this.startAction = action;
this.enumerator = enumerator;
}
public OneAction(Action action)
{
this.startAction = action;
this.enumerator = null;
}
///
/// 自定义的协程
///
class CustomEnumerator : IEnumerator
{
public object Current => null;
Func IsCompleted;
public CustomEnumerator(Func IsCompleted)
{
this.IsCompleted = IsCompleted;
}
public bool MoveNext()
{
return !IsCompleted();
}
public void Reset()
{
}
}
}
}