Unity 协程与线程

协程是不同台的

协程 不是 线程,协同程序是
不同步 的

     
一个线程在先后中以及其余线程是异步运行的,在多处理器机器中一个线程可以而且跟拥有其他线程的实时运行该代码,这使线程编程能够化解很复杂的政工,因为可能在同等的流年里一个线程在变更她而另外一个线程正在读取它,这意味任何一个线程实际上可以转移之事物在游戏受拍卖的中像是您的源代码一行。这是盖若写的代码是由于机械变成汇编语言,更是再次复杂。正因这么,你得经过锁,以保证这种气象不见面由于另外保管无共享内存发生。或者经过锁定任何线程使用同一片内存,当他俩于读取或变更时。

哎是协程?

     
协同程序绝对不是一个线程。这意味当同一时间只生一个协同程序在履,它见面给执行于玩耍之主线程上,所以实际在同一时间游戏的骨干只发一个协同程序在运作[立马段翻译的匪极端可靠]

*     你永远不需操心联合还是锁定一个值当你在编写一个协同程序。你生出了的控制权,直到你的代码执行到
yiedld*

  因此总结一下协程的概念

   
协程只是有实行,并要在适合的原则得满足,在未来底之一平等随时以受恢复,直到她的做事就

Unity函数执行图

Unity processes coroutines every frame of the game for every object that
has one or more running.  The processing occurs after Update and before
LateUpdate for most yield statements, but there are special cases:

Unity的流水线协同程序在玩乐的各国一样轴每个对象也具一个还是多单正在运转的。Update()
之后,LateUpdate()之前 ,发生的 yield 语词的拍卖,但为有特别情况

图片 1

When the coroutine is activated it will execute right up to the next
yield statement and then it will pause until it is resumed.  You can see
where it will resume in the diagram above, based on what you yield.

当协程被激活,它见面直接到下一个
yield语句执行,然后她会中断,直到其过来。你可在直达图被视她会死灰复燃,根据你的
yield语句。

粗略的协程示例

深受我们来探望一个非常简单的协程

IEnumerator TestCoroutine()
{
      while(true)
      {
           Debug.Log(Time.time);
           yield return null;
      }
}

拖欠协程将会晤永远执行下。它记录时之日子,然后yield,当它于还原,它而入了这轮回,记录同一不善时间,遇到
yield 并再度之前的操作

The code inside the loop is exactly like an Update function.  It
runs once every frame for this object, just after the script’s Update
routine runs (if it has one).

随即代码循环就比如 Update() 函数。这个目标在各级一样轴中运作,脚本的Update
程序运行后(如果有的话)

When you call StartCoroutine(TestCoroutine()) the code executes
immediately up to the first time it yields, it will then be resumed when
Unity processes coroutines for this object.

当你调用 StartCoroutine(TestCoroutine()) 代码立即第一次得到推行 然后
yield,当Unity 引擎再次拍卖这GameObject时,协程会叫还原

If you start a coroutine early in the
processing of a game object, like creating one in Start, Update or
OnCollisionEnter then that coroutine will immediately run up to the
first yield, then it will resume during the same frame if you yield
return null .

设若你在早于Unity处理到GameObject就实施一个协程
比如
Start(),Update()或OnCollisionEnter()将会继续执行,当第一不良遇到yield,然后同一帧会恢复,如果您yield
null。有时候会有意外的结果,如果您不考虑她。

 

是不是会极其循环

现行尚发同桩事,在我们的测试协程显然不是极致循环

下列情况协程将会见不再叫执行:如果您回打电话,会停下游戏对象的协同程序,如果它们为销毁,它不见面重新运行。如果下论为一直或经玩对象上利用SetActive(false),它为无会见另行实践。

I Yield Sir

Unity processes coroutines every frame of the game for every object that
has one or more running.

Unity于处理协程时是
在嬉戏的各个一样幅,每一个GameObject上展开的,可以处理1个或多单

你也许也想啊,不,它不欲,如果您采取这样的

yield return new WaitForSeconds(1)then it
doesn’t process it for another 1 second!”那么它们不处理它的另外1秒Well
actually Unity does process that coroutine every frame, checking to see
if the right amount of time has elapsed – it doesn’t process your code,
but it does process the coroutine which is the wrapper its made around
your script.那么实际上,Unity
会处理协程在各个一样幅,检查合适的岁月是否都过去,它不见面处理你的代码,但是她会处理此协程,是若的脚本在包装这个协程因此我们知晓,我们可中的中断我们的代码通过
yield ,下面是那些你得Return 的:

  • null
    -协程执行下同样不善,它是合格的
  • WaitForEndOfFrame –
    协程的框架上推行,在享有的渲染和图形用户界面完成以后
  • WaitForFixedUpdate –
    导致这个协程在生一致不成物理学的步调执行,在备的物理计算后
  • WaitForSeconds –
    使协程并无是一个特定的游戏时间内实施
  • WWW –
    waits for a web request to complete (resumes as if WaitForSeconds or
    null)
  • Another
    coroutine – in which case the new coroutine will run to completion
    before the yielder is
    resumed(在这种状况下,新的协同程序将以这个Yield恢复之前就)

You
can also issue the command yield break; which immediately stops the
coroutine.你还好起 yield break
命令,去立停止这协程Because of
WaitForEndOfFrame coroutines can be used to get information from render
textures when all cameras have completed rendering and the GUI has been
displayed因为
WaitForEndOfFrame 协程可以用来自渲染纹理中获取信息,
当所有的Camera已好渲染 并且 GUI 已经于显示Using
yield return new WaitForSeconds(x) will never resume if the
Time.timeScale is set to 0.采取 yield
return new WaitForSeconds(x) 将永久不见面被还原,如果 Time.timeScale
=0Of course
the great thing about all of this is that you can write code that needs
to execute over a period of time, or wait for some external event to
occur, and keep it all nicely together in a single function making your
code far more readable than if you had to write multiple functions or
lots of code to keep checking the state of things.当然,关于这整个的丕之事务是,你得写用执行一段时间,或者等待发生一些表事件,并保持其富有时尚典雅的一致起于一个纯的效能一旦您的代码更易于读的代码比,如果您不得不编写多只函数的代码或地面继续检查东西之状态。这是真的协同程序的境界。

 

总结:

  1. Coroutines are
    a really good way of making a sequence of operations happen over
    time or when some external process is completed
  2. Coroutines are
    not threads and are not asynchronous
  3. Nothing else
    is running when your coroutine is executing
  4. Your coroutine
    will resume when the conditions of your yield statement are met

  5. Coroutines are
    inactive when the script is disabled or the object is destroyed

  6. yield return new
    WaitForSeconds is dependent on game time which is affected by
    Time.timeScale

译:

  1. 协程通过以梯次的操作 或局部实际的拍卖 当它成功时
  2. 协程并无是线程,它从不一起
  3. 没有外 或就当运行协程
  4. 公的协程

 

协程的其实用途

期咱们曾经知道了协程是呀,以及它以运转时。我们的高档教程将研究该技术以她身后

给我们为此协程做片作业。几个简易的支援函数,使用协程可以叫我们创建好切割的队列

我们可以描绘一个协同的运动目标及对象位置及旋转。我们得描绘一个协程的等动画是一个特定的完成百分比。然后用就半只器,
我们可以死爱地修脚论在一个单一的功能,其中其见面十分容易看全切序列

使用协程,通过顾其以倒,为的凡使确保不见面起其它的协程或Update()函数里改变它的职务于同一时间确保您唯有发生一个协程影响GameObject在同一时间,禁用Update()
函数 移动目标

协程动画演示

这里发生一个一块的一个例证等待动画部分形成

//Wait for an animation to be a certain amount complete
IEnumerator WaitForAnimation(string name, float ratio, bool play)
{
    //Get the animation state for the named animation
    var anim = animation[name];
    //Play the animation
    if(play) animation.Play(name);

    //Loop until the normalized time reports a value
    //greater than our ratio.  This method of waiting for
    //an animation accounts for the speed fluctuating as the
    //animation is played.
    while(anim.normalizedTime + float.Epsilon + Time.deltaTime < ratio)
        yield return new WaitForEndOfFrame();

}

You could write a coroutine to wait for an animation like this:

IEnumerator Die()
{
       //Wait for the die animation to be 50% complete
       yield return StartCoroutine(WaitForAnimation("die",0.5f, true));
       //Drop the enemies on dying pickup
       DropPickupItem();
       //Wait for the animation to complete
       yield return StartCoroutine(WaitForAnimation("die",1f, false));
       Destroy(gameObject);
}

资料

英文原稿:http://unitygems.com/coroutines/

发表评论

电子邮件地址不会被公开。 必填项已用*标注