【发布时间】:2017-05-10 07:39:22
【问题描述】:
我试图弄清楚如何在 Unity 协程中正确使用 UnityWebRequest,我尝试了这种方式,但没有得到结果:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Networking;
public class rest : MonoBehaviour
{
public Coroutine<T> StartCoroutine<T>(IEnumerator coroutine)
{
Coroutine<T> coroutineObj = new Coroutine<T>();
coroutineObj.coroutine = base.StartCoroutine(coroutineObj.InternalRoutine(coroutine));
return coroutineObj;
}
public class Coroutine<T>
{
public T Value
{
get
{
if (e != null)
{
throw e;
}
return returnVal;
}
}
private T returnVal;
private Exception e;
public Coroutine coroutine;
public IEnumerator InternalRoutine(IEnumerator coroutine)
{
while (true)
{
try
{
if (!coroutine.MoveNext())
{
yield break;
}
}
catch (Exception e)
{
this.e = e;
yield break;
}
object yielded = coroutine.Current;
if (yielded != null && yielded.GetType() == typeof(T))
{
returnVal = (T)yielded;
yield break;
}
else
{
yield return coroutine.Current;
}
}
}
}
IEnumerator Start()
{
var routine = StartCoroutine<int>(TestNewRoutineGivesException());
yield return routine.coroutine;
try
{
Debug.Log(routine.Value);
}
catch (Exception e)
{
Debug.Log(e.Message);
Debug.Break();
}
}
IEnumerator TestNewRoutineGivesException()
{
yield return null;
yield return new WaitForSeconds(5f);
UnityWebRequest www = UnityWebRequest.Get("http://localhost:3000/api/players");
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.Send();
while (!www.downloadHandler.isDone) yield return new WaitForEndOfFrame();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
string results = www.downloadHandler.text;
yield return results;
}
}
}
但如果我的 TestNewRoutineGivesException 看起来像这样,那么它可以工作
IEnumerator TestNewRoutineGivesException()
{
yield return null;
yield return new WaitForSeconds(5f);
yield return new 100;
}
它将返回“100”
【问题讨论】:
-
错误是什么?
-
在创建
www对象后尝试显式创建www.downloadHandler。我记得我也遇到了一些问题。试试这个:www.downloadHandler = new DownloadHandlerBuffer();之前yield return www.Send(); -
也许,以防万一,尝试在协程中等待:
while(!www.downloadHandler.isDone) yield return new WaitForEndOfFrame(); -
我已经更新了代码以反映更改,但它仍然无法正常工作。没有错误,问题是它返回 0 而不是实际输出。
-
我认为你不能从协程中返回太多次.. 看起来它在第一次
yield return www.Send();之后就卡住了