在unity中,协程是一个特殊的函数,它经过使用yield语句中断执行当前的代码,直到中断指令(YieldInstruction)结束后再接着以前的代码继续执行。web
在C#中写协程须要遵循的规则有: 1.协程的返回值必须是IEnumerator 2.协程的参数不能有 ref或out的关键字 3.在C#脚本中,必须经过StartCoroutine来启动协程 4.yield语句要用yield return来代替。 5.在MonoBehaviour子类的Update和FixedUpdate函数里不能使用yield语句,但能够启动协程。 下面是使用C#写协程的例子:
using UnityEngine;
using System.Collections;
public class TestCorutine : MonoBehaviour {
// Use this for initialization
IEnumerator Start () {
print("Start");
yield return new WaitForSeconds(5);//1.程序会在这里等待5s后再往下执行。
print( "after Wait" );
StartCoroutine( DoFunc() );//2.使用StartCoroutine启动了协程
print("After StartCoroutine");
}
IEnumerator DoFunc()
{
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>hello I'm DoFunc");
yield return new WaitForSeconds(10);
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>End DoFunc");
}
}
//执行的结果
//Start
//after Wait
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>hello I'm DoFunc
//After StartCoroutine
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>End DoFunc
unity中协程相关的类有:WaitForSeconds、WaitForFixedUpdate、Coroutine、WaitForEndOfFrame、AsyncOperation。
经常使用的yield return语句有:svg
形式 | 意义 |
---|---|
yield return null | 等待下一帧中的update行完后再继续执行 |
yield return new WaitForSeconds(10) | 延迟10s后执行 |
yield return new WaitForFixedUpdate() | 等待全部的脚本的FixedUpdate函数执行完后在继续执行 |
yield return new WWW(url) | 等待url下载完后再继续执行 |
yield return StartCoroutine(MyFunc) | 等待协程MyFunc执行完后再执行 |
StartCoroutine函数是MonoBehaviour的一个类成员函数。函数
public Coroutine StartCoroutine(IEnumerator routine);
public Coroutine StartCoroutine(string methodName);
public Coroutine StartCoroutine(string methodName, [DefaultValue("null")] object value);
全部StartCoroutine只能在MonoBehaviour或者其子类中使用,它只接收协程函数名字,或者IEnumerator实例做为参数。this
在untiy中使用StopCoroutine来终止一个协程,使用StopAllCoroutine终止全部该MonoBehaviour中能终止的协程。还有一种方法是将MonoBehaviour脚本挂载的GameObject的active属性设为false.
最后yield return不能使用在try-catch语句块中,但能够写在try-finally语句快的try语句块中。不能写在匿名方法中,不能写在unsafe语句块中url