Search code examples
c#unity-game-engine

How to make a GET request without Monobehaviour or System.IO (using while loop?)


I am trying to make a GET request but cannot use System.IO, or Monobehaviour (I am working on a Warudo mod).

So far I have the code below. MakeRequest half the time returns the values I want, so I know at least the request is coming through, but half the time it returns an empty string (or whatever I initiate text with). Is there a reason the while loop breaks off early (if that is what it's doing), and/or is there a better way of making this request?

edit: I thought adding && text == "" to the while loop would do the trick, but it still returns an emtpy string half the time

private string MakeRequest()
{
    var text = "";
    var getRequest = CreateRequest(URL).SendWebRequest();
    while (!getRequest.isDone)
    {
        if (getRequest.isDone)
        {
            text = getRequest.webRequest.downloadHandler.text;
        }
    }
    return text;
}
private UnityWebRequest CreateRequest(string path)
{
    var request = new UnityWebRequest(path, "GET");
    request.downloadHandler = new DownloadHandlerBuffer();
    request.SetRequestHeader("Content-Type", "application/json");

    return request;
}

Solution

  • You do

    while (!getRequest.isDone)
    {
        if (getRequest.isDone)
        {
    

    so you tell me how big is the probability that exactly between the two lines while and if the request finishes so your if check succeeds?

    Very very small!

    Why not rather move it after the request finishes

    Besides that I would also place some check whether the request succeeded at all by checking the result first.

    private string MakeRequest()
    {
        var getRequest = CreateRequest(URL).SendWebRequest();
        while (!getRequest.isDone)
        {
           // in general not a good idea to do empty loops like this
        }
    
        if(getRequest.webRequest.result != UnityWebRequest.Result.Success)
        {
            throw new Exception(getRequest.webRequest.error);
        }
    
        return getRequest.webRequest.downloadHandler.text;
    }
    

    This will of course still cause a complete freeze until the request is done and put some heavy load on the CPU running your loop all the time.


    Still I wouldn't go for completely freezing implementations but rather go async. There are many ways depending on your exact use case and needs.

    Either use a normal Task<string> or UniTask<string> or the new Awaitables. None of these require a MonoBehaviour