C# 在下载的同时从UnityWebRequest获取数据?
我有以下代码来进行REST调用:C# 在下载的同时从UnityWebRequest获取数据?,c#,unity3d,networking,yield,C#,Unity3d,Networking,Yield,我有以下代码来进行REST调用: public IEnumerator GetCooroutine(string route) { string finalURL = URL + route; UnityWebRequest www = UnityWebRequest.Get(finalURL); yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) {
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
,代码将等待发送
完成它的执行,我不希望这样。可以使用UnityWebRequest
执行,但您必须执行额外的工作。秘诀是将DownloadHandlerScript
与UnityWebRequest
一起使用
创建一个单独的类,并使其派生自DownloadHandlerScript
,而不是MonoBehavior
。在下面的示例中,我将其称为CustomWebRequest
。重写bool ReceiveData(byte[]data,int-dataLength)
,void CompleteContent()
及其内部的void ReceiveContentLength(int-contentLength)
函数
下面是CustomWebRequest
类的一个示例:
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));
}
}
就这样
- Unity首次发出请求时,
被调用。您可以使用ReceiveContentLength(int contentLength)
参数来确定将从该请求接收的总字节数contentLength
- 每次接收到新数据时,都会调用
函数 通过该功能,您可以从ReceiveData
参数及其从byteFromServer
参数dataLength
- 当Unity完成接收数据时,
功能被激活 打电话来CompleteContent
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();
}