一个协同程序在执行过程中,可以在任意位置使用yield语句。yield的返回值控制何时恢复协同程序向下执行。协同程序在对象自有帧执行过程中堪称优秀。协同程序在性能上没有更多的开销。StartCoroutine函数是立刻返回的,但是yield可以延迟结果。直到协同程序执行完毕。
function StartCoroutine(routine : IEnumerator) : Coroutine
One example:
usingUnityEngine;
usingSystem.Collections;
public classexample : MonoBehaviour {
void Start() {
print("Starting " + Time.time);//firstprint
StartCoroutine(WaitAndPrint(2.0F));
print("BeforeWaitAndPrint Finishes " + Time.time);//secondprint
}
IEnumerator WaitAndPrint(floatwaitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint" + Time.time);//lastprint
}
}
IEnumerable是一个声明式的接口,声明实现该接口的class是“可枚举(enumerable)”的,但并没有说明如何实现枚举器(iterator);IEnumerator是一个实现式的接口,IEnumeratorobject就是一个iterator(通过MoveNext(),Reset(),Current)。
Another example:
function StartCoroutine(methodName : string, value : object = null) : Coroutine
// In this example we show how toinvoke a coroutine using a string name and stop it
// 这个例子演示如何调用一个使用字符串名称的协同程序并停掉它
functionStart () {
StartCoroutine("DoSomething",2.0);
yield WaitForSeconds (1);
StopCoroutine("DoSomething");
}
functionDoSomething (someParameter : float) {
while (true) {
print("DoSomethingLoop");
// Yield execution of this coroutineand return to the main loop until next frame
//停止协同程序的执行并返回到主循环直到下一帧.
yield;
}
}