如何等待StartCoroutine()完成后再继续
本文关键字:再继续 StartCoroutine 等待 何等待 | 更新日期: 2023-09-27 18:00:27
我正在编写一段代码,从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
}
}
}
然后只需调用查询。
注意:如果调用yield return wwwQuery,则无需忙于等待。如果你不想这样做,你应该忙着等待,例如,你想检查下载进度,在这种情况下,你应该在MonoBehavior中定义的Update方法内轮询www类的结果。
try:
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类的.NET版本。