I have this code that makes a REST call:
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);
}
}
I need to access the data or body of the request while they are receiving, and use it for other stuff. I don't want to wait until it has finished receiving them before accessing them.
If I use yield
, the code waits until the send
finishes it's execution, and I don't want that.
It is possible to do it with
UnityWebRequest
but you have to perform extra work. The secret is to useDownloadHandlerScript
withUnityWebRequest
.Create a separate class and make it derive from
DownloadHandlerScript
instead ofMonoBehaviour
. In the example below, I will call itCustomWebRequest
. Override thebool ReceiveData(byte[] data, int dataLength)
,void CompleteContent()
and thevoid ReceiveContentLength(int contentLength)
functions inside it.Here is an example of the
CustomWebRequest
class:And to use it to start the download, just create new instance of
UnityWebRequest
and useCustomWebRequest
as thedownloadHandler
before calling theSendWebRequest
function. No coroutine required for this and you don't even have to yield anything. This is how to do it:That's it.
When Unity first makes the request,
ReceiveContentLength(int contentLength)
is called. You can use thecontentLength
parameter to determine the total number of bytes you will receive from that request.The
ReceiveData
function is called each time new data is received and from that function, you can access that current data from thebyteFromServer
parameter and the length of it from thedataLength
parameter.When Unity is done receiving data, the
CompleteContent
function is called.