DEV Community

Piler
Piler

Posted on

[Unity] use UnityWebRequest by async/without coroutine

UnityWebRequestAsync class:

using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

public static class UnityWebRequestAsync
{
    public async static Task<string> Request(string url, RequestMethod method, string body = null)
    {
        if (string.IsNullOrEmpty(url))
        {
            Debug.LogError("URL cannot be null or empty.");
            return null;
        }

        string[] arr = new string[]
        {
            "GET",
            "POST",
            "PUT",
            "DELETE"
        };

        using UnityWebRequest request = new UnityWebRequest(url, arr[(int)method]);
        try
        {
            // Setup
            if (method != RequestMethod.GET && body != null)
            {
                byte[] jsonDataBytes = Encoding.UTF8.GetBytes(body);
                request.uploadHandler = new UploadHandlerRaw(jsonDataBytes);
            }

            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("version", Application.version);

            // Send request
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }

            // Check Result
            if (request.result == UnityWebRequest.Result.Success)
            {
                return request.downloadHandler.text;
            }
            else
            {
                Debug.LogError($"Request failed: {request.error} (HTTP {request.responseCode})");
                return null;
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"Exception occurred during request: {ex.Message}");
            return null;
        }
    }
}

public enum RequestMethod
{
    GET,
    POST, 
    PUT, 
    DELETE
}
Enter fullscreen mode Exit fullscreen mode

Usage:

string result = await UnityWebRequestAsync.Request(url, RequestMethod.GET);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)