---
title: 编写和运行协程
product: Unity Editor
version: '6000.0'
latest_version: '7000.0'
status: This page documents version 6000.0. The latest version is 7000.0.
canonical: https://docs.unity.com/zh-cn/engine/6000.0/manual/scripting/object-oriented-development/coroutines-section/coroutines
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/scripting/object-oriented-development/coroutines-section/coroutines.md
generated_at: 2026-11-16T06:34:11.574Z
locale: zh-cn
---

# 编写和运行协程

> 编写并运行协程方法，以完成在多个帧特效的工作，例如逐渐淡化特效。

协程是可以暂停执行并在稍后时间恢复的方法。在 Unity Applications 中，这意味着协程可以在一帧中 Start running，然后在另一帧中恢复，从而允许将任务扩散到多个帧。

常规非协程方法运行到完成，然后将 Control 返回到调用方，在 Unity 运行时意味着它们的 Action 在单一帧更新内完成。如果希望某个方法的工作在多个帧特效（例如逐渐淡化特效），可以使用协程。协程还可用于处理长时间的异步操作，例如等待 HTTP 传输、资源加载或文件 I/O 完成。

> **Important:**
>
> 不要将协程与线程混淆。协程中运行的 Synchronous 操作仍然 ON 主要线程执行。如果要减少主要线程花费的 CPU 时间，避免协程中的阻挡操作与 Any Other 脚本代码中的阻挡操作同样重要。如果要在 Unity 中使用多线程代码，可以选项：

* [任务系统](/engine/6000.0/manual/scripting/optimization/job-system.md)
* .NET [异步和等待](/engine/6000.0/manual/scripting/optimization/async-await-support.md)以及 Unity 的自定义`Awaitable` Support

## 编写协程##writing-coroutines

请考虑逐渐减小Object的 Alpha（不透明度）值直到其不可见的任务。为了使淡入淡出特效可见，不透明度必须在一系列帧中降低。如果尝试编写`Fade`方法，可以编写如下内容：

```lang-cs
void Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
    }
}
```

此方法不是协程，因此在单一帧更新内执行其 `for` Loop 的每个迭代，Object 会立即消失，而不是看起来淡化。一种可能的解决方案是向`Update`函数添加代码，该函数逐帧执行 ON 淡化。但是，使用协程可能更方便。

协程是[`IEnumerator`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator) return type and a [ yield](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield) return statement included somewhere in the body. The `yield return` 语句是暂停执行的点的方法。以前的`Fade`方法可以重写为协程，如下所示：

```lang-cs
IEnumerator 淡化 ()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
        返回 null
    }
}
```

该方法的此版本在其 `for` Loop 执行一次迭代，然后在 `yield return null` 语句处暂停执行。它会在 Next 帧中恢复并执行 Loop 的另一次迭代，依此类推 ON，使逐渐淡化特效可见。`Fade` 方法中的 Loop 计数器在协程的 Lifetime 中保持其正确值，并且在 `yield` 语句之间保留 Any 变量或参数。

## 启动和停止协程##starting-and-stopping-coroutines

要设置运行协程，请使用 [StartCoroutine](/engine/6000.0/script-reference/unityengine/monobehaviour/startcoroutine.md) 方法：

```lang-cs
void Update()
{
    if (Input.GetKeyDown("f"))
    {
        StartCoroutine(Fade());
    }
}
```

要停止协程，请使用 [StopCoroutine](/engine/6000.0/script-reference/unityengine/monobehaviour/stopcoroutine.md) 和 [StopAllCoroutines](/engine/6000.0/script-reference/unityengine/monobehaviour/stopallcoroutines.md)。在以下情况下，协程也会停止：

* [`GameObject.activeSelf`](/engine/6000.0/script-reference/unityengine/gameobject/activeself.md) 的值成为脚本所挂的游戏对象的`false`。
* MonoBehaviour 脚本通过调用 [Destroy](/engine/6000.0/script-reference/unityengine/object/destroy.md) 进行销毁。

> **Note:**
>
> 通过将[已启用](/engine/6000.0/script-reference/unityengine/behaviour/enabled.md)设置为 `false` 来禁用 MonoBehaviour 脚本不会停止协程。

## 恢复协程##resuming-coroutines

When an suspended conroude continue execution depends ON the yield instructions in the `yield return` 语句中提供的 yield 指令。下一帧恢复`yield return null`。Unity 有一设置自定义定义产量指令，使用于在指定时间后、满足指定条件When或在播放PlayerLoop中的指定的点继续。有关更多信息，请参阅[产量指令参考](/engine/6000.0/manual/scripting/object-oriented-development/coroutines-section/coroutines-yield-instructions.md)。

在淡化特效示例中，您可能希望淡入淡化特效以比帧率率更低和更一致的Rate发生。您可以`yield return` [`WaitForSeconds`](/engine/6000.0/script-reference/unityengine/waitforseconds.md) 指令，在`Fade`方法的迭代之间引入已修复的时间延时，如下所示：

```lang-cs
IEnumerator 淡化 ()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
        // Wait for 0.1 seconds before the next iteration
        返回 新建 WaitForSeconds(.1f);
    }
}
```

还可以从协程中`yield return` Unity [`Awaitable`](/engine/6000.0/script-reference/unityengine/awaitable.md)。如果要将协程与使用`async`和`await`的异步代码集成，这将很有用。例如，在前面的示例中，您可以`yield return Awaitable.WaitForSecondsAsync(.1f)`而不是`yield return new WaitForSeconds(.1f)`来实现相同的特效。

> **Important:**
>
> 不支持从协程`yield return` Generic [`Awaitable<T0>`](/engine/6000.0/script-reference/unityengine/awaitable1.md)。

## 编辑模式下的协程##coroutines-in-edit-mode

协程主要是运行时功能。关联的[运行时生成指令](/engine/6000.0/manual/scripting/object-oriented-development/coroutines-section/coroutines-yield-instructions.md)位于 `UnityEngine` 命名空间中，以 Editor 的播放模式或独立平台 Player 运行。如果您的脚本使用 [`[ExecuteInEditMode]`](/engine/6000.0/script-reference/unityengine/executeineditmode.md) 或 [`[ExecuteAlways]`](/engine/6000.0/script-reference/unityengine/executealways.md) Attributes，它们也可以在编辑模式下运行，但编辑模式下的更新 Loop 不像 Player Loop 那样已修复和定期。

对于专为以编辑模式运行的协程，使用 [Editor Coroutines 包](https://docs.unity3d.com/Packages/com.unity.editorcoroutines@latest)。

## 测试中的协程##coroutines-in-tests

Unity Test Framework 带有 `[UnityTest]` 属性的播放模式测试作为协程运行，并允许从测试中为 Unity Editor 生成自定义指令。有关更多信息，请参阅 [Yield 指令 Editor](/engine/6000.0/manual/reference-custom-yield-instructions.md)。

## coroutine性性能##coroutine-performance

协程如果滥用，可能会导致隐藏分配和垃圾回收器尖峰。每个协程创建一个[`IEnumerator`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator)状态机。频繁启动它们（例如，帧）会分配和增加开销。`yield return null` 不会分配，但会生成像 `new WaitForSeconds` 一样的指令。缓存常用对象，避免在[`WaitUntil`](/engine/6000.0/script-reference/unityengine/waituntil.md)和[`WaitWhile`](/engine/6000.0/script-reference/unityengine/waitwhile.md)中使用 lambda，以防止委托和捕获分配。

首选与 `yield return null` Loop 循环的长效协程，而不是反复启动新建协程。缓存或已修复持续时间的池[`WaitForSeconds`](/engine/6000.0/script-reference/unityengine/waitforseconds.md)。协程保留对其所有者和捕获的变量的引用。确保以[`MonoBehaviour.StopCoroutine`](/engine/6000.0/script-reference/unityengine/monobehaviour/stopcoroutine.md)结束或停止，以避免泄漏。

始终进行性能配置文件，尤其是ON受约束的平台上，以Confirm和定位分配。有关更多信息，请参阅[分析协程](/engine/6000.0/manual/scripting/object-oriented-development/coroutines-section/coroutines-analyzing.md)。

## 其他资源##additional-resources

* [coroutine API 参考](/engine/6000.0/script-reference/unityengine/coroutine.md)
* [MonoBehaviour.StartCoroutine](/engine/6000.0/script-reference/unityengine/monobehaviour/startcoroutine.md)
