如何等待协程回调执行?

Yos*_*oto 2 c# unity-game-engine

我想等待 StartCoroutine 回调被执行。有人知道该怎么做吗?

public float getXXX() {
  var result;
  StartCoroutine(YYY((r) => result = r)); // how to wait this?
  return result;
}

private IEnumerator YYY(System.Action<float> callback) {
  LinkedList<float> list = new LinkedList<float>();
  while(timeleft > 0) {
    timeleft -= Time.deltaTime;
    list.add(transform.position.magnitude);
    yield return new WaitForSeconds (WAITSPAN);
  }

  callback(list.max());
  yeild return true;
}
Run Code Online (Sandbox Code Playgroud)

Pro*_*mer 5

您不能也不应该尝试等待或让出协程函数从协程函数(getXXX函数)返回。它将阻塞该非协程函数,直到该函数返回,从而阻止其他 Unity 脚本运行。

要在函数中等待协程 function( YYY) getXXX,您还必须将正在调用并等待的函数置于协程函数中。在本例中,这是YYY函数,因此它也应该是一个协程函数,那么您可以yield

public IEnumerator getXXX()
{
    float result = 0f;
    yield return StartCoroutine(YYY((r) => result = r)); // how to wait this?

    //Use the result variable
    Debug.Log(result);
}
Run Code Online (Sandbox Code Playgroud)

或者

如果您不想使该getXXX函数成为协程函数,则不要尝试在那里等待。您仍然可以使用协程函数的结果YYY,但不要尝试返回结果。只需使用它在该函数中执行您想做的任何操作即可:

public void doSomethingXXX()
{
    StartCoroutine(YYY((result) =>
    {
        //Do something with the result variable
        Debug.Log(result);

    }));
}
Run Code Online (Sandbox Code Playgroud)

使用协程的想法是能够在多个帧上执行某些操作。void 函数只会在一帧内执行此操作。您不能在voidIEnumerator/coroutine 函数或非 IEnumerator/coroutine 函数中让出/等待。