这里himi强调一点:unity里面的协程并不是线程,协程是在unity主线程中运行的,每一帧中处理一次,而并不与主线程并行。这就意味着在协程之间并不存在着所谓线程间的同步和互斥问题,不会出现死锁。一般来说,访问同一个值也都是很安全的,用协程可以处理绝大多数的小问题,而且不用考虑复杂的线程间同步,还是很方便的。
要说协程的不足就是不能运用处理器的多核来提高处理性能,毕竟这个在运行时事实上是在一个线程中执行的。
【以下均为转载内容】
在unity中,延时执行一段代码或者一个方法或者几个方法的情况非常普遍。
一般会用到invoke和invokerepeating方法。顾名思义,第一个是执行一次,第二个是重复执行。
看下定义:
void invoke(string methodname, float time);
第一个参数是方法名(注意是字符串形式),并不是更方便的委托。第二个是延时多少秒。只执行一次。
void invokerepeating(string methodname, float time, float repeatrate);
invokerepeating第二个参数是延时多少秒后开始,第三个参数是每次执行间隔的秒数。
你有没有发现这两个方法有个弊端,就是必须输入方法名!也就是我说,如果我想延时执行某段代码,必须把代码放在某个方法里,然后使用这invoke或者invokerepeating方法来执行。
这样对于上下文变量、属性的引用就会尤为不便,而且不能传参数!!!尼玛,要他还有何用?
我猜你一定用过这样的方法。没错,“协同”,听起来还挺高大上的名字啊。
用startcoroutine来执行一个以ienumerator为返回值的方法,通常用于异步下载啊,等比较耗时又不能让游戏卡死的情况。
还有一个好的类waitforseconds,对,它就一个构造函数,用来延时的(延时………………比万艾可好用?比希爱力好用?)。
好了不废话了,以下是我自用的延时方法,放在一个类里以静态方法存在。可以在任何时候任何地方延时指定秒数的代码。
using unityengine;
using system.collections;
using system;
public class delaytoinvoke : monobehaviour
{
public static ienumerator delaytoinvokedo(action action, float delayseconds)
yield return new waitforseconds(delayseconds);
action();
}
如何使用呢?
比如我点击ngui的一个button,则
void onclick()
startcoroutine(delaytoinvoke.delaytoinvokedo(() =>
application.loadlevel(“option”);
}, 0.1f));
尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com
记得去年6月份刚开始实习的时候,当时要我写网络层的结构,用到了协程,当时有点懵,完全不知道unity协程的执行机制是怎么样的,只是知道函数的返回值是ienumerator类型,函数中使用yield return ,就可以通过startcoroutine调用了。后来也是一直稀里糊涂地用,上网google些基本都是例子,很少能帮助深入理解unity协程的原理的。
本文只是从unity的角度去分析理解协程的内部运行原理,而不是从c#底层的语法实现来介绍(后续有需要再进行介绍),一共分为三部分:
线程(thread)和协程(coroutine)
unity中协程的执行原理
ienumerator & coroutine
d.s.qiu觉得使用协程的作用一共有两点:1)延时(等待)一段时间执行代码;2)等某个操作完成之后再执行后面的代码。总结起来就是一句话:控制代码在特定的时机执行。
很多初学者,都会下意识地觉得协程是异步执行的,都会觉得协程是c# 线程的替代品,是unity不使用线程的解决方案。
所以首先,请你牢记:协程不是线程,也不是异步执行的。协程和 monobehaviour 的 update函数一样也是在mainthread中执行的。使用协程你不用考虑同步和锁的问题。
unitygems.com给出了协程的定义:
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.
即协程是一个分部执行,遇到条件(yield return 语句)会挂起,直到条件满足才会被唤醒继续执行后面的代码。
unity在每一帧(frame)都会去处理对象上的协程。unity主要是在update后去处理协程(检查协程的条件是否满足),但也有写特例:
从上图的剖析就明白,协程跟update()其实一样的,都是unity每帧对会去处理的函数(如果有的话)。如果monobehaviour 是处于激活(active)状态的而且yield的条件满足,就会协程方法的后面代码。还可以发现:如果在一个对象的前期调用协程,协程会立即运行到第一个 yield return 语句处,如果是 yield return null ,就会在同一帧再次被唤醒。如果没有考虑这个细节就会出现一些奇怪的问题『1』。
『1』注 图和结论都是从unitygems.com 上得来的,经过下面的验证发现与实际不符,d.s.qiu用的是unity 4.3.4f1 进行测试的。经过测试验证,协程至少是每帧的lateupdate()后去运行。
下面使用 yield return new waitforseconds(1f); 在start,update 和 lateupdate 中分别进行测试:
using unityengine;
using system.collections;
public class testcoroutine : monobehaviour {
private bool isstartcall = false; //makesure update() and lateupdate() log only once
private bool isupdatecall = false;
private bool islateupdatecall = false;
// use this for initialization
void start () {
if (!isstartcall)
{
debug.log(“start call begin”);
startcoroutine(startcoutine());
debug.log(“start call end”);
isstartcall = true;
}
}
ienumerator startcoutine()
{
debug.log(“this is start coroutine call before”);
yield return new waitforseconds(1f);
debug.log(“this is start coroutine call after”);
// update is called once per frame
void update () {
if (!isupdatecall)
debug.log(“update call begin”);
startcoroutine(updatecoutine());
debug.log(“update call end”);
isupdatecall = true;
ienumerator updatecoutine()
debug.log(“this is update coroutine call before”);
debug.log(“this is update coroutine call after”);
void lateupdate()
if (!islateupdatecall)
debug.log(“lateupdate call begin”);
startcoroutine(latecoutine());
debug.log(“lateupdate call end”);
islateupdatecall = true;
ienumerator latecoutine()
debug.log(“this is late coroutine call before”);
debug.log(“this is late coroutine call after”);
得到日志输入结果如下:
然后将yield return new waitforseconds(1f);改为 yield return null; 发现日志输入结果和上面是一样的,没有出现上面说的情况:
yield return null;
『今天意外发现monobehaviour的函数执行顺序图,发现协程的运行确实是在lateupdate之后,下面附上:』
增补于:03/12/2014 22:14
经过验证,『2』的结论也是错误的,正确的结论是,monobehaviour.enabled = false 协程会照常运行,但 gameobject.setactive(false) 后协程却全部停止,即使在inspector把 gameobject 激活还是没有继续执行:
this.enabled = false;
//this.gameobject.setactive(false);
debug.log(“this is update coroutine call second”);
先在update中调用 this.enabled = false; 得到的结果:
然后把 this.enabled = false; 注释掉,换成 this.gameobject.setactive(false); 得到的结果如下:
整理得到:通过设置monobehaviour脚本的enabled对协程是没有影响的,但如果 gameobject.setactive(false) 则已经启动的协程则完全停止了,即使在inspector把gameobject 激活还是没有继续执行。也就说协程虽然是在monobehvaviour启动的(startcoroutine)但是协程函数的地位完全是跟monobehaviour是一个层次的,不受monobehaviour的状态影响,但跟monobehaviour脚本一样受gameobject 控制,也应该是和monobehaviour脚本一样每帧“轮询” yield 的条件是否满足。
yield 后面可以有的表达式:
a) null – the coroutine executes the next time that it is eligible
b) waitforendofframe – the coroutine executes on the frame, after all of the rendering and gui is complete
c) waitforfixedupdate – causes this coroutine to execute at the next physics step, after all physics is calculated
d) waitforseconds – causes the coroutine not to execute for a given game time period
e) www – waits for a web request to complete (resumes as if waitforseconds or null)
f) another coroutine – in which case the new coroutine will run to completion before the yielder is resumed
值得注意的是 waitforseconds()受time.timescale影响,当time.timescale = 0f 时,yield return new waitforsecond(x) 将不会满足。
ienumerator & coroutine
unity在每帧做的工作就是:调用 协程(迭代器)movenext() 方法,如果返回 true ,就从当前位置继续往下执行。
hijack
这里在介绍一个协程的交叉调用类 hijack(参见附件):
using system;
using system.collections.generic;
using system.linq;
[requirecomponent(typeof(guitext))]
public class hijack : monobehaviour {
//this will hold the counting up coroutine
ienumerator _countup;
//this will hold the counting down coroutine
ienumerator _countdown;
//this is the coroutine we are currently
//hijacking
ienumerator _current;
//a value that will be updated by the coroutine
//that is currently running
int value = 0;
void start()
//create our count up coroutine
_countup = countup();
//create our count down coroutine
_countdown = countdown();
//start our own coroutine for the hijack
startcoroutine(dohijack());
void update()
//show the current value on the screen
guitext.text = value.tostring();
void ongui()
//switch between the different functions
if(guilayout.button(“switch functions”))
if(_current == _countup)
_current = _countdown;
else
_current = _countup;
ienumerator dohijack()
while(true)
//check if we have a current coroutine and movenext on it if we do
if(_current != null && _current.movenext())
{
//return whatever the coroutine yielded, so we will yield the
//same thing
yield return _current.current;
}
//otherwise wait for the next frame
yield return null;
ienumerator countup()
//we have a local increment so the routines
//get independently faster depending on how
//long they have been active
float increment = 0;
//exit if the q button is pressed
if(input.getkey(keycode.q))
break;
increment+=time.deltatime;
value += mathf.roundtoint(increment);
yield return null;
ienumerator countdown()
float increment = 0f;
value -= mathf.roundtoint(increment);
//this coroutine returns a yield instruction
yield return new waitforseconds(0.1f);
上面的代码实现是两个协程交替调用,对有这种需求来说实在太精妙了。
小结:
今天仔细看了下unitygems.com 有关coroutine的两篇文章,虽然第一篇(参考①)现在验证的结果有很多错误,但对于理解协程还是不错的,尤其是当我发现hijack这个脚本时,就迫不及待分享给大家。
本来没觉得会有unitygems.com上的文章会有错误的,无意测试了发现还是有很大的出入,当然这也不是说原来作者没有经过验证就妄加揣测,d.s.qiu觉得很有可能是unity内部的实现机制改变了,这种东西完全可以改动,unity虽然开发了很多年了,但是其实在实际开发中还是有很多坑,越发觉得unity的无力,虽说容易上手,但是填坑的功夫也是必不可少的。
看来很多结论还是要通过自己的验证才行,贸然复制粘贴很难出真知,切记!