协程

                                                         协程

什么是协程?

       协同程序绝对不是一个线程。这意味着在同一时间只有一个协同程序在执行,它会被执行在游戏的主线程上,所以实际上在同一时间游戏的核心只有一个协同程序在运行[这段翻译的不太好]

       你永远不需要担心同步或锁定一个值当你正在编写一个协同程序。你有完全的控制权,直到你的代码执行到 yiedld

因此总结一下协程的定义:

          协程只是部分执行,并假定在适当的条件得到满足,在未来的某一时刻将被恢复,直到它的工作完成

          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语句

让我们来看看一个非常简单的协程

        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。有时候会有奇怪的结果,如果你不考虑它。

   以上是数据库的初步了解,如果你有什么不会的话,可以来狗刨学习网上来看看,如果你想在Unity3D上大展手脚的话,可以来狗刨培训与专家咨询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值