unity中使用协程的时候,会经常遇到两个问题。
- 绑定在GameObject上的协程,会因为Active false而终止运行。
- 当使用一个协程的时候,如果注册一个通过的回调函数,来处理结果,并且可以拿到协程返回的值。
第一个问题,可以使用一个协程管理器。挂在独立的GameObject上,不会受到操作的GameObject的active状态影响。
第二个问题,在协程函数里,自然我们拿到协程完成的结果,并调用回调。但是不够通用,需要在每个协程函数里写同样的调用。我们可以通过给协程注入一个回调函数来统一处理,并传入协程的返回值。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public static class ACoroutineManager
{
private class InnerCoroutine : MonoBehaviour {}
private static InnerCoroutine coroutine;
static ACoroutineManager()
{
if (coroutine == null)
{
coroutine = new GameObject("ACoroutineManager").AddComponent<InnerCoroutine>();
GameObject.DontDestroyOnLoad(coroutine);
}
}
public static Coroutine StartCoroutineTask(IEnumerator routine)
{
r