如何在继续之前等待 StartCoroutine() 完成

How to wait for a StartCoroutine() to finish before proceeding

我正在编写一段代码,从 MySQL 获取一条信息并将其显示在 UI 上。问题是,程序不会等待 MySQL 查询完成,而是直接显示变量(它是空的,因为查询结果没有按时显示)

我的代码大纲如下:

bool notYetDone = true;

StartCoroutine(query(web));

IEnumerator query (WWW web){
    yield return web;
    while(notYetDone == true){
        yield return new WaitForSeconds(1f);
        if(web.error == null){
            //no problems with the query, some code here
            notYetDone = false;
        } else if (web.error != null){
            //some code here for handling errors
        } else {
            Debug.Log("i dont really know why we reached here");
        }
    }
}

我还注意到,它似乎改变了 notYetDone 的值并立即结束循环。我的代码有问题吗?提前致谢。

试试这个:

class QueryBehaviour: MonoBehaviour
{
  bool queryFinished = false;
  WWW wwwQuery;

  IEnumerator Query()
  {
    wwwQuery = new WWW("url_to_query");
    yield return wwwQuery;

    queryFinished = true;
    //results or error should be here
  }

  Update()
  {
    if( queryFinished == false )
    {
      return;
    }
    else
    {
      //use wwwQuery here
    }
  }
}

然后调用查询

注意:调用yieldreturnwwwQuery不需要忙等。如果你不想这样做,你应该忙着等待,例如,你想检查一个下载进度,在这种情况下,你应该在 Update 中轮询 www class 的结果MonoBehaviour.

中定义的方法

尝试:

IEnumerator query (WWW web)
{
   //yield return web;
   while(!web.isDone && web.Error == null)
   {
    //this will loop until your query is finished
    //do something while waiting...
      yield return null;
   }
   if(web.Error != null)
     Debug.Log("Errors on web");

}

将 yield 关键字放在 startcoroutine 之前也会有同样的效果。你的情况:

yield StartCoroutine(query(web)); 
//at this point it is guaranteed to be completed

http://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

使用回调怎么样?

   public void showMessage(string message)
    {
        setMessage(message);
        Debug.Log("start_fadeIn");
        StartCoroutine(coroutine__fadeIn(delegate
        {
            Debug.Log("start_fadeOut");
            StartCoroutine(coroutine__fadeOut(delegate
            {
                Debug.Log("done");
            }));
        }));
    }


    private IEnumerator coroutine__fadeIn(Action completion)
    {
        CanvasGroup canvasGroup = GetComponent<CanvasGroup>();
        for (float f = 0f; f <= 1; f += 0.01f)
        {
            canvasGroup.alpha = f;
            yield return null;
        }

        completion();
    }

    private IEnumerator coroutine__fadeOut(Action completion)
    {
        CanvasGroup canvasGroup = GetComponent<CanvasGroup>();
        for (float f = 1f; f >= 0; f -= 0.01f)
        {
            canvasGroup.alpha = f;
            yield return null;
        }

        completion();
    }

警告,此方法需要使用支持 Action class.

的 .NET 版本