我有这段代码可以进行 REST 调用:
public IEnumerator GetCooroutine(string route)
{
string finalURL = URL + route;
UnityWebRequest www = UnityWebRequest.Get(finalURL);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
Debug.Log("GET succesfull. Response: " + www.downloadHandler.text);
}
}
我需要在接收时访问请求的数据或正文,并将其用于其他用途。我不想等到它完成接收它们才访问它们。
如果我使用yield
,代码等待直到send
完成它的执行,我不希望这样。
这是可以做到的UnityWebRequest
但你必须执行额外的工作。秘诀就是使用DownloadHandlerScript
with UnityWebRequest
.
创建一个单独的类并使其派生自DownloadHandlerScript
代替MonoBehaviour
。在下面的例子中,我将其称为CustomWebRequest
。覆盖bool ReceiveData(byte[] data, int dataLength)
, void CompleteContent()
和void ReceiveContentLength(int contentLength)
里面有函数。
这是一个例子CustomWebRequest
class:
public class CustomWebRequest : DownloadHandlerScript
{
// Standard scripted download handler - will allocate memory on each ReceiveData callback
public CustomWebRequest()
: base()
{
}
// Pre-allocated scripted download handler
// Will reuse the supplied byte array to deliver data.
// Eliminates memory allocation.
public CustomWebRequest(byte[] buffer)
: base(buffer)
{
}
// Required by DownloadHandler base class. Called when you address the 'bytes' property.
protected override byte[] GetData() { return null; }
// Called once per frame when data has been received from the network.
protected override bool ReceiveData(byte[] byteFromServer, int dataLength)
{
if (byteFromServer == null || byteFromServer.Length < 1)
{
Debug.Log("CustomWebRequest :: ReceiveData - received a null/empty buffer");
return false;
}
//Do something with or Process byteFromServer here
return true;
}
// Called when all data has been received from the server and delivered via ReceiveData
protected override void CompleteContent()
{
Debug.Log("CustomWebRequest :: CompleteContent - DOWNLOAD COMPLETE!");
}
// Called when a Content-Length header is received from the server.
protected override void ReceiveContentLength(int contentLength)
{
Debug.Log(string.Format("CustomWebRequest :: ReceiveContentLength - length {0}", contentLength));
}
}
要使用它来开始下载,只需创建新的实例UnityWebRequest
并使用CustomWebRequest
as the downloadHandler
在致电之前SendWebRequest
功能。不需要协程,你甚至不需要产生任何东西。操作方法如下:
UnityWebRequest webRequest;
//Pre-allocate memory so that this is not done each time data is received
byte[] bytes = new byte[2000];
void Start()
{
string url = "http://yourUrl/mjpg/video.mjpg";
webRequest = new UnityWebRequest(url);
webRequest.downloadHandler = new CustomWebRequest(bytes);
webRequest.SendWebRequest();
}
就是这样。
当 Unity 第一次发出请求时,ReceiveContentLength(int
contentLength)
叫做。您可以使用contentLength
参数来确定您将从该请求收到的总字节数。
The ReceiveData
每次收到新数据时都会调用该函数
通过该函数,您可以从以下位置访问当前数据byteFromServer
参数及其长度dataLength
范围。
当 Unity 完成接收数据后,CompleteContent
函数是
叫。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)