协程--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语句有:
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
- 协程--Coroutine小记
- Coroutine 协程
- Coroutine(协程)
- coroutine协程
- Coroutine协程
- 协程coroutine
- Gevent 协程(coroutine)
- Boost coroutine 协程
- Lua 协程 coroutine
- 协程coroutine资料更新
- 协程(coroutine)
- tornado协程(coroutine)原理
- lua协程coroutine
- tornado.gen.coroutine-协程
- Unity协程(Coroutine)
- Unity Coroutine协程
- unity “协程”Coroutine
- Boost coroutine 协程
- 我干了一件傻事,在ViewController的subclass中企图使用initWithFrame
- 在github上浏览html文件
- 勾股定理一日一证连载132
- Android 编程下两种方式注册广播的区别
- 数字签名过程
- 协程--Coroutine小记
- JSON
- AutoLayout2
- TeamTalk编译连接过程中遇到的问题及解决方法(iOS)(1)
- Git 笔记
- VC资源分配、释放表
- Socket
- android 横竖屏切换生命周期
- <sudt-ACM>数据结构实验之链表八:Farey序列