unity学习日记-协程

最近在学习unity,涉及到协程的部分,还是总结一下吧。进入正文。
协程听起来有点像线程,但是协程(Coroutine)不是线程(Thread),协程创建于一个线程,一个线程可以有多个协程。在线程里面开启协程,让程序在特定的时间内运行。可以比喻:程序员相当于OS,协程就相当于进程或是线程。也就是说,协程基本是由程序员控制,负责进行调度。而线程是由OS进行调度的。

协程的定义:
A coroutine is a function that is executed partially and, presuming suitable conditions are met, will be resumed at some point in the future until its work is done.
这是我自己的翻译:
协程是一个函数,它是分部地被执行。在未来的某个时刻,当假设的适当的条件满足以后将会继续执行到它的工作完成。(满足yeild return后)
何谓部分执行?这是因为协程有挂起的状态,当条件满足的时候,将会继续执行后面的程序。yield return条件语句将会挂起。
接下来,看一下Monobehaviour的函数执行顺序图:
函数执行顺序图

图中可以看出协程(Coroutine)是在Update()之后调用的。
协程继承自IEnumerator(迭代器),IEnumerator 接口中其中两个方法 Current 和 MoveNext() ,只有MoveNext()返回true时,才可以访问。current在调用 MoveNext 或 Reset 之前,Current 返回同一对象。MoveNext 将 Current 设置为下一个元素。
Unity在每帧做的工作就是:调用 协程(迭代器)MoveNext() 方法,如果返回 true ,就从当前位置继续往下执行。
至于关于IEnumerator 接口,这儿有篇博客:
http://www.cnblogs.com/kivenhou/archive/2009/10/23/1588709.html

yield 后面的条件有:

Normal coroutine updates are run after the Update function returns. A coroutine is function that can suspend its execution (yield) until the given given YieldInstruction finishes. Different uses of Coroutines:

null;The coroutine will continue after all Update functions have been called on the next frame.
yield WaitForSeconds(2);Continue after a specified time delay, after all Update functions have been called for the frame
yield WaitForFixedUpdate();Continue after all FixedUpdate has been called on all scripts
yield WWWContinue after a WWW download has completed.
yield StartCoroutine(MyFunc); Chains the coroutine, and will wait for the MyFunc coroutine to complete first.

需要什么,就用什么。具体用的话,以后再慢慢用,先搞清楚概念~~

小结:对协程有了初步的认识,还需要在以后的日子里不断学习。如果文中有错误的地方,还请看到的人及时地批评指正。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值