Skip to content
On this page

Unity 协程

什么是协程?

协程(Coroutine)是Unity中用于处理异步操作的一种机制。它允许你在不阻塞主线程的情况下执行一系列操作,这对于处理动画、等待、定时任务等非常有用。

协程与普通方法的主要区别在于:

  • 协程可以暂停执行(yield),并在之后从暂停点继续
  • 协程不会阻塞主线程
  • 协程可以跨越多帧执行

如何创建和启动协程?

在Unity中,协程是通过定义一个返回类型为IEnumerator的方法来创建的。然后,你可以通过调用StartCoroutine方法来启动这个协程。

基础示例

csharp
using System.Collections;
using UnityEngine;

public class ExampleCoroutine : MonoBehaviour
{
    void Start()
    {
        // 启动协程
        StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        Debug.Log("协程开始");
        // 等待2秒
        yield return new WaitForSeconds(2);
        Debug.Log("2秒后");
        // 等待下一帧
        yield return null;
        Debug.Log("下一帧");
    }
}

实用示例:倒计时

csharp
IEnumerator Countdown(int seconds) {
    while (seconds > 0) {
        Debug.Log(seconds);
        yield return new WaitForSeconds(1);
        seconds--;
    }
    Debug.Log("倒计时结束!");
}

void Start() {
    StartCoroutine(Countdown(5));
}

常见应用场景

  1. 延迟执行
  2. 分帧处理大数据
  3. 网络请求等待
  4. 动画序列控制
  5. 资源加载

注意事项

  1. 协程不是线程,仍然运行在主线程上
  2. 协程中的无限循环会导致游戏卡死
  3. 协程可以被StopCoroutine停止
  4. 协程在对象被销毁时会自动停止
  5. 避免在Update中频繁启动协程

Released under the MIT License.