unity中coroutine(2)

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

在C#中写协程需要遵循的规则有:
1.协程的返回值必须是IEnumerator
2.协程的参数不能有 ref或out的关键字
3.在C#脚本中,必须通过StartCoroutine来启动协程
4.yield语句要用yield return来代替。
5.在MonoBehaviour子类的Update和FixedUpdate函数里不能使用yield语句,但可以启动协程。

下面是使用C#写协程的例子:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

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); 
  • 1
  • 2
  • 3

所有StartCoroutine只能在MonoBehaviour或者其子类中使用,它只接收协程函数名字,或者IEnumerator实例作为参数。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值