Arzie100 发表于 2022-4-19 10:45

Unity Coroutine 协程

协程(Coroutine)和线程(Threads)听起来类似,但实际上是完全不同的东西,首先要明白 Coroutine 跟 Threads 是两码事。
A coroutine allows you to spread tasks across several frames. In Unity, a coroutine is a method that can pause execution and return control to Unity but then continue where it left off on the following frame.
这里已经写得很清楚了,Coroutine 可以做到在这一 frame 停止运行然后在下一 frame 继续。官方文档给的例子是一个物体逐渐褪色的效果:
void Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
      c.a = alpha;
      renderer.material.color = c;
    }
}
如果我们把它放在 Update 中,我们并不会看到这个效果,因为这个 for loop 会很快执行完毕。我们可能会想到使用 Thread.Sleep 在for loop 每次执行变化 alpha 之后等一段时间。但更好的方式就是使用 Coroutine:
IEnumerator Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
      c.a = alpha;
      renderer.material.color = c;
      yield return null;
    }
}
IEnumerator 和 yield 是把一个方法变成 Coroutine 的关键词。 yield 这一句就是停止这个函数和回来继续执行的点,然后我们也要用 StartCoroutine 来开始 Coroutine:
void Update()
{
    if (Input.GetKeyDown("f"))
    {
      StartCoroutine(Fade());
    }
}
The yield return nullline is the point where execution pauses and resumes in the following frame. To set a coroutine running, you need to use the StartCoroutine function.
所以,执行顺序是类似:
Update → Fade → 遇到 yield → 停止 → Update(新的frame) → 回到 yield 继续
当然我们也可以在 Coroutine 中引入 WaitForSeconds,这样延迟一段时间而不是下一个 frame 就继续。
重要的是我们需要知道:
However, it’s important to remember that coroutines aren’t threads. Synchronous operations that run within a coroutine still execute on the main thread. If you want to reduce the amount of CPU time spent on the main thread, it’s just as important to avoid blocking operations in coroutines as in any other script code. If you want to use multi-threaded code within Unity, consider the C# Job System.
官方文档中也提到了建议使用 Coroutine 的地方包括比如如果需要长时间等待的异步操作,比如:

[*]HTTP transfer
[*]asset loads
[*]file I/O
而正是因为它的适用情况,所以经常跟 Thread 配合在一起。比如 Easy Threading With Coroutines 中的例子。
参考:

[*]Coroutines
[*]WaitForSeconds
[*]Easy Threading With Coroutines
页: [1]
查看完整版本: Unity Coroutine 协程