UnityWebRequest not working consistently

Hello,
I am trying to load in level data from a csv file. Since I want to be able to do this on an android phone I am using UnityWebRequests. The code works most of the time but sometimes the level data seems to be empty. I can’t figure out why it is working so inconsistently.
Any insight would be greatly appreciated,
Thank you

IEnumerator GetRequest(string uri)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
        {
            // Request and wait for the desired page.
            webRequest.SendWebRequest();
            level_data = webRequest.downloadHandler.text;
            //yield return webRequest.SendWebRequest();
            yield return null;

            string[] pages = uri.Split('/');
            int page = pages.Length - 1;

            switch (webRequest.result)
            {
                case UnityWebRequest.Result.ConnectionError:
                case UnityWebRequest.Result.DataProcessingError:
                    Debug.LogError(pages[page] + ": Error: " + webRequest.error);
                    break;
                case UnityWebRequest.Result.ProtocolError:
                    Debug.LogError(pages[page] + ": HTTP Error: " + webRequest.error);
                    break;
                case UnityWebRequest.Result.Success:
                    Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
                    break;
            }
        }
    }

why did you comment out line 8?

            //yield return webRequest.SendWebRequest();

you need to actually wait for the webrequest to finish, and yield return null just tells unity to wait for a tick (the web request could still not be finished after that).

Also, webRequest.downloadHandler.text will only have data after you’ve properly waited for the web request to finish. Move it past line 8.

2 Likes

The comment on line 5 is a lie.

As Jason points out, that just merely triggers a request.

You commented out the waiting part.

But good props to you for the using() statement! Those are unfortunately frequently omitted in network example code in Unity, leading to potential un-Dispose()d resources.

1 Like

Thank you guys for the help!

1 Like