5.3.8版本测试URL请求,没有超时机制,网络出现问题时程序将一直卡住
UnityWebRequest requestDownload = UnityWebRequest.Get(url);
yield return requestDownload.Send();
UnityWebRequest.Send返回的是一个AsyncOperation,增加一个“计时器”包装一下:
public class TimeoutAsyncOperation : IEnumerator
{
private long _BeginTime;
private int _TimeoutMS;
public AsyncOperation AsyncOperation;
public bool IsTimeout { get; private set; }
public TimeoutAsyncOperation(AsyncOperation asyncOpr, int timeoutMS)
{
AsyncOperation = asyncOpr;
_TimeoutMS = timeoutMS;
_BeginTime = Util.GetTime();
}
public object Current
{
get
{
return null;
}
}
public bool MoveNext()
{
return !IsDone();
}
public void Reset()
{
}
public bool IsDone ()
{
if (AsyncOperation.isDone)
{
IsTimeout = false;
return true;
}
else
{
long now = Util.GetTime();
if (now - _BeginTime >= _TimeoutMS)
{
IsTimeout = true;
return true;
}
return false;
}
}
}
使用也很简单:
UnityWebRequest requestServerList = UnityWebRequest.Get(url);
{
TimeoutAsyncOperation asynOpr = new TimeoutAsyncOperation(requestServerList.Send(), 1000 * 10);
yield return asynOpr;
if (asynOpr.IsTimeout)
{
// 超时处理
}
if (requestServerList.isError)
{
//返回错误
}
// 读取内容
string content = Encoding.UTF8.GetString(requestServerList.downloadHandler.data);
}