跳至主要内容

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 语句的处理,但也有特殊情况
Overview
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/

评论

此博客中的热门博文

[3D跑酷] AudioManager

Unity音频管理 游戏中的声音管理最常用的组件莫过于AudioSource和AudioClip,我的做法是建立是一个AudioManager类(单例类)管理各个音频,谈一下我的经验: 函数列表 Start函数:设置音频整体参数; 编辑器面板 拖拽文件赋值 AudioSource文档 逻辑实现代码 public void playSoundEffect(SoundEffects soundEffect) { AudioClip clip = null ; float pitch = 1; switch (soundEffect) { case SoundEffects.ObstacleCollisionSoundEffect: clip = obstacleCollision; break ; case SoundEffects.CoinSoundEffect: clip = coinCollection; pitch = 1.5f; break ; case SoundEffects.PowerUpSoundEffect: clip = powerUpCollection; break ; case SoundEffects.GameOverSoundEffect: clip = gameOver; break ; case SoundEffects.GUITapSoundEffect: clip = guiTap; break ; } soundEffectsAudio.pitch = pitch; //音调 so...

[3D跑酷] GUIManager UI管理

UI元素更新及界面跳转 继上篇日志《Unity开发之 GUIClickEventReceiver》,再谈一下我们如何管理游戏中的UI元素更新及界面跳转 UI绑定 图一:Inspector面板 Public GameObjectName与GameObject一一对应 UI结构及命名规范 图二:Hierarchy面板 UI父子结构及组件命名规范 UI枚举种类 图三:enum GUIState UI绑定代码 图四:public UI控件定义 与Hierarchy命名规范 UI主要方法及逻辑 图五:主要方法及逻辑 主要方法 1、隐藏Transform及子Transform #if !UNITY_3_5 private void activeRecursively(Transform obj, bool active) { foreach (Transform child in obj) { activeRecursively(child, active); } obj.gameObject.SetActive(active); } #endif private GameObject panelFromState(GUIState state) { switch (state) { case GUIState.MainMenu: return mainMenuPanel; case GUIState.InGame: return inGamePanel; case GUIState.EndGame: return endGamePanel; case GUIState.Store: return storePanel; case GUIState.Stats: return statsPanel; case GUISt...

谷歌Adsense广告代码异步加载解决谷歌联盟广告老卡的问题

最近一段时间,谷歌中国的服务器从香港撤走,导致很多朋友连谷歌也无法访问了,而像部落这样,在网站中投放了谷歌Adsense广告的,也经常会出 现网站打开,加载到谷歌广告位置时,网站就卡在那里了,估计一些网速慢的用户,可能就永远卡那里了。对于这种情况,我们可以利用异步加载的广告代码来解决 这个问题。 Google广告会因为各种原因经常打不开,如果不用异步加载的方法,会导致在您的网站中,google广告后面的代码显示被阻塞,这样的话,很影响用户体验。经常网页不能完全打开的话,必然会导致用户的在面积流失。 上图是部落的网站首页,在没有使用广告代码异步加载前,经常会出现这样的现像,首页右边的一个300X300的谷歌广告位无法正常显示了。 当然,使用谷歌Adsense广告代码异步加载,您的网站加载速度会明显提升,特别是对一些网速慢的用户来说,但有一点和我们站长相矛盾的,那就是上次谷歌承诺广告发布商的广告被有效浏览才收费,很明显,异步加载有可能会降低您站内广告的浏览量。 使用谷歌Adsense广告代码异步加载 其实使用方法很简单,我们进入自己的谷歌联盟后台,在“广告单元”中找到需要异步加载的广告位,点击“获取代码”,如下图: 我们在代码类型中选择“异步”,就能获得异步加载的广告位代码,将您之前在网站中投放的广告代码替换就行了。 之前传统的google广告异步加载代码 不知您有没有发现,之前传统的google广告异步加载代码之这次部落所说的有很大的不同了,例如部落之前同样是采用的广告代码同步加载,代码内容如下: --> 显然,以上代码会影响您的网站加载速度。而之前的异步加载代码,则是在后面加上了一段JS代码。内容就不放出了。 部落在谷歌官方找到一些异步加载说明:google广告在google服务器正常的情况下会及时的正常显示,google服务器不正常的情况下也不会影响后面页面的加载。 而自己正式体验后,才发现,谷歌联盟的广告加载速度真是超快,只是加载的内容,匹配性没之前那么好了,究其原因,部落猜想应该是在调用本地电脑数据的cookis时,就直接调用了其中的广告数据,只有这样,加载速度才会达到最快。当然,这纯粹只是个人猜想而已。