在Unity中,协程(Coroutine)的概念类似于线程,他是一种特殊的函数,能中断(通过yield语句)执行当前的代码,知道中断命令(YieldInstruction)结束之后再接着之前的代码继续执行。以下是一个示例:
IEnumerator WaitAndPrint()
{
yield return new WaitForSeconds(5);
print("WaitAndPrint"+Time.time);
}
//上面的协程表示等待5秒钟后输出当前时间。
1) 协程的返回值必须是IEnumerator
2)协程的参数不能加关键字ref或者out
3) 在c#脚本中,必须通过StartCoroutine来启动协程
4)yield语句要用yield return 来替代
5)在函数Update和FixedUpdate中不能使用yield语句,但可以启动协程。
在Unity中,绝大部分协程相关的类都继承自基类YieldInstruction,唯一例外的就是类WWW,它不继承自YieldInstruction,但可以用在yield return语句中。
#WaitForSeconds()受Time.timeScale影响,当Time.timeScale为0时,yield return new WaitForSecond(n)将失效。
StartCoroutine用于启动协程,声明:
public Coroutine StartCoroution(IEnumerator routine);
public Coroutine StartCoroution(string methodName,object value=null);
从上面声明中可以看出:
1)StartCoroution只能在MonoBehaviour或其子类中使用。
2)StartCoroution接收协程名称(字符串)或IEnumerator实例作为参数。