Method containing "yield return" never gets executed

78 views Asked by At

I have just written the following function.

private IEnumerator getData()
{
    string url = "http://localhost:3000/data";
    using (UnityWebRequest request = UnityWebRequest.Get(url))
    {
        yield return request.SendWebRequest();
        switch (request.result)
        {
            case UnityWebRequest.Result.ConnectionError:
            case UnityWebRequest.Result.DataProcessingError:
            case UnityWebRequest.Result.ProtocolError:
                Debug.LogError("The request has failed: " + request.error);
                break;
            case UnityWebRequest.Result.Success:
                Debug.Log("Here is our data: " + request.downloadHandler.text);
                break;
        }
    }
}

It should retrieve a simple string from a backend, but even if I call it it never gets executed. I first tried to call it in this way:

IEnumerator data = getData();
Debug.Log(data);

But it didn't work. Then I tried to use a foreach but it didn't work either:

IEnumerator data = getData();
foreach(var x in data) {
    Debug.Log(x);
}

How can I call this function?

2

There are 2 answers

1
maraaaaaaaa On

Your method must return an IEnumerable, not IEnumerator

private IEnumerable getData()
{
    string url = "http://localhost:3000/data";
    using (UnityWebRequest request = UnityWebRequest.Get(url))
    {
        yield return request.SendWebRequest();
        switch (request.result)
        {
            case UnityWebRequest.Result.ConnectionError:
            case UnityWebRequest.Result.DataProcessingError:
            case UnityWebRequest.Result.ProtocolError:
                Debug.LogError("The request has failed: " + request.error);
                break;
            case UnityWebRequest.Result.Success:
                Debug.Log("Here is our data: " + request.downloadHandler.text);
                break;
        }
    }
}
0
nix86 On

AztecCodes is right: the getData method needs to be called with StartCoroutine. Therefore the solution is:

StartCoroutine(getData());