假设我想调用汽车的一些方法,例如drive(30, 5)
、rotate(45)
、stop()
。
我如何拥有方法队列,例如[drive(30,5), rotate(45), stop()]
以便我可以执行第一个函数,等到它结束并调用下一个函数?
所有这些方法都是协程(IEnumerators
(。
var ms = new List<Action>()
{
() => drive(30, 5),
() => rotate(45),
() => stop()
};
for (int i = 0; i < ms.Count; i++)
{
ms[i](); // Invoke
}
是的,使用 C# 操作和协程可以! 以下是所有伪代码,但可以详细说明! 想象!
Using System;
public class SomeClass : MonoBehaviour
{
myDefaultWaitTime = SomeFloat;
myQueue = new List<Action>();
void AddAction(Action myNewAction)
{
myQueue.Add(myNewAction);
}
Action myNextAction()
{
Action myAction = myQueue[0];
myQueue.delete(0);
return myAction;
}
IEnumerator WaitToLoad(Action myAction)
{
float currentWaitTime = 0;
while (currentWaitTime < defaultWaitTime)
{
currentWaitTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
StartCoroutine(myNextAction());
}
}
public IEnumerator Drive(int x, int y)
{
// driving routine here.
}
public IEnumerator Rotate(float angle)
{
// rotation routine here.
}
public IEnumerator Stop()
{
// Stop routine here
}
public IEnumerator ExecuteAll()
{
// Drive
yield return new StartCoroutine(Drive(30,5));
// rotate
yield return new StartCoroutine(Rotate(45));
// Stop
yield return new StartCoroutine(Stop());
// All actions are done.
}
public void StartAll()
{
StartCoroutine(ExecuteAll());
}