协程--Coroutine小记

来源:互联网 发布:福建广电网络集团张远 编辑:程序博客网 时间:2024/06/05 05:16

在unity中,协程是一个特殊的函数,它通过使用yield语句中断执行当前的代码,直到中断指令(YieldInstruction)结束后再接着之前的代码继续执行。

在C#中写协程需要遵循的规则有:1.协程的返回值必须是IEnumerator2.协程的参数不能有 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语句有:

形式 意义 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实例作为参数。

在untiy中使用StopCoroutine来终止一个协程,使用StopAllCoroutine终止所有该MonoBehaviour中能终止的协程。还有一种方法是将MonoBehaviour脚本挂载的GameObject的active属性设为false.
最后yield return不能使用在try-catch语句块中,但可以写在try-finally语句快的try语句块中。不能写在匿名方法中,不能写在unsafe语句块中

0 0
原创粉丝点击