什么是协程?
协同程序绝对不是一个线程。这意味着在同一时间只有一个协同程序在执行,它会被执行在游戏的主线程上,所以实际上在同一时间游戏的核心只有一个协同程序在运行[这段翻译的不太准确] 你永远不需要担心同步或锁定一个值当你正在编写一个协同程序。你有完全的控制权,直到你的代码执行到 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 语句的处理,但也有特殊情况
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语句。 简单的协程示例
让我们来看看一个非常简单的协程
该协程将会永远执行下去。它记录当前的时间,然后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.当然,关于这一切的伟大的事情是,你可以写需要执行一段时间,或者等待发生一些外部事件,并保持它拥有时尚典雅的一起在一个单一的功能使你的代码更易读的代码比,如果你不得不编写多个函数的代码或地段继续检查事物的状态。这是真正的协同程序的地步。总结:
Coroutines are a really good way of making a sequence of operations happen over time or when some external process is completed
Coroutines are not threads and are not asynchronous
Nothing else is running when your coroutine is executing
Your coroutine will resume when the conditions of your yield statement are met
Coroutines are inactive when the script is disabled or the object is destroyed
yield return new WaitForSeconds is dependent on game time which is affected by Time.timeScale
//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);
}