【unity2D】API-学习记录8-协程Coroutine

目标

理解协程的工作机制并掌握它的使用方法

基于API理解协程

UnityAPI对协程Coroutine的解释

Coroutine

A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes.
协同程序是一个可以暂停执行 (yield) 的函数,直到给定的 YieldInstruction 完成。

即协程能够暂停协程函数的执行,直到给定的 YieldInstruction 完成,再从之前暂停的地方继续执行下去

UnityAPI对 YieldInstruction 的解释

YieldInstruction

Base class for all yield instructions.
所有 yield 指令的基类。

也就是说,我们可以利用 YieldInstruction 来暂停协程函数的执行

UnityAPI中协程函数的代码范例(片段)

private IEnumerator WaitAndPrint(float waitTime)
{
    yield return new WaitForSeconds(waitTime);
    print("Coroutine ended: " + Time.time + " seconds");
}

从上面我们可以看出一些端倪,协程函数和函数有一些地方不同:

  1. 协程没有返回值,它被IEnumerator修饰。IEnumerator英文意为迭代器,它是C#库里用来声明迭代器的一种语法。不必研究它的起源,只要知道:IEnumerator在Unity里是协程的标志。

  2. 协程用yield return代替return,并且至少要有一个yield。协程从yield处开始暂停,直到满足yield后给出的条件。

常用yield指令

参考简单总结协程Coroutine及Yield常见用法

yield null;//这一帧暂停,在下一帧所有的Update函数都执行完了之后再执行
yield return new WaitForSeconds(0.1f);//等待五秒后再执行,受Time.timeScale影响
yield return new WaitForSecondsRealtime(0.1f);//等待五秒后再执行,不受Time.timeScale影响

如何启动协程

使用StartCoroutine();

第一种:变量版本

private IEnumerator coroutine;//创建IEnumerator变量
coroutine = WaitAndPrint(2.0f);//带参赋值,这里的WaitAndPrint是一个已经写好了的协程
StartCoroutine(coroutine);//开始协程

第二种:字符串版本

StartCoroutine("DoSomething", 2.0f);

第二种虽然只用了一行代码,非常易读。但它相比第一种有两个缺点:

  1. 字符串版本在启动协程时的运行时开销更高。
  2. 并且只能传递一个参数。

如何终止协程

使用StopCoroutine();

以下是API中的解释:

StopCoroutine 接受以下三个参数(用于指定要停止的协同程序)之一:

  1. 一个字符串函数,用于命名激活的协同程序
  2. 之前用于创建该协同程序的 IEnumerator 变量。
  3. 一个 /Coroutine/,用于停止手动创建的 /Coroutine/。

注意:不要混淆三个参数,用何种参数启动协程的,以对应参数结束之

如果使用了字符串作为 StartCoroutine 中的参数,请在 StopCoroutine 中使用该字符串。

同样,在 StartCoroutine 和 StopCoroutine 中使用相同的 StopCoroutine。

最后才为 StopCoroutine 使用创建时使用的 /Coroutine/。

参考资料

Unity API Coroutine
Unity API MonoBehaviour.StartCoroutine
Unity API MonoBehaviour.StCoroutine
协程(Coroutine)原理分析
简单总结协程Coroutine及Yield常见用法

上一篇:协程


下一篇:基于NtyCo的协程使用和API