How to return value from UnityWebRequest?

I have a script that connects to the database and retrieve data. The GetData function is called by other script. is there a way that I can return the data back to the caller?

public IEnumerator GetData(){
    using (UnityWebRequest wwww = UnityWebRequest.Get("http://localhost/BMS/LoadGame.php")) {
        yield return wwww.SendWebRequest();

        if (wwww.isNetworkError || wwww.isHttpError){
            Debug.Log(wwww.error);
        } else {
            Debug.Log(wwww.downloadHandler.text);

            //How to return the result to the caller?
        }
    }
}

The method that I know is to call another function in other script to pass the data, but this is a lot more troublesome. Is there any direct way that I can return the data to the caller? Thanks!

No, there is no other way. Doing a synchronous http request would block your whole execution until it’s done this could take several seconds. Even when it’s relatively quick it will mostly take at least around 20ms which would have a huge impact on your framerate.

The only alternative is to do whatever you want to do on a seperate thread. However as you may know you can’t use most of the Unity API from other threads. Also doing synchronous web requests or using threads may not be supported at all depending on your target platform. (WebGL for example).

So the only reasonable way is to use a callback. When you use your method inside another coroutine you can actually wait for your coroutine and it’s almost like a synchronous call. For example:

public IEnumerator GetData(System.Action<string> aOnData)
{
    // [ ... ]
    if (aOnData != null)
        aOnData(wwww.downloadHandler.text);
}

When using this inside another coroutine you can do:

IEnumerator DoStuff()
{
    // [ ...]
    string data = "";
    yield return StartCoroutine(GetData(s=>data = s));
    // use "data" here
}

Of course in order to wait for another coroutine to finish you have to call it from within a coroutine. Always keep in mind that almost the whole scripting environment of Unity runs on the main thread. Actually blocking the thread would block your whole application.