Unity – need to return value only after coroutine finishes

Functions don’t wait for coroutines before return, however you could use an Action to give some kind of return.

Put this in your Start function

WWW www = new WWW("http://google.com");

StartCoroutine(WaitForRequest(www,(status)=>{
    print(status.ToString());
}));

and add this.

private IEnumerator WaitForRequest(WWW www,Action<int> callback) {
    int tempInt = 0;
    yield return www;
    if (string.IsNullOrEmpty(www.error)) {
        if(!string.IsNullOrEmpty(www.text)) {
            tempInt = 3;
        }
        else {
            tempInt=2;
        }
    } else {
        print(www.error);
        tempInt=1;
    }
    callback(tempInt);
}

Give this a try, although the function can change a value it doesn’t return a value and only has a single parameter. So in essence this isn’t a solution for returning your coroutine however once received the int from the coroutine we are then able to justify what to do with it and even call other functions from within the callback.

StartCoroutine(WaitForRequest(www,(status)=>{
    print(status.ToString());
    Awake(); // we can call other functions within the callback to use other codeblocks and logic.
    if(status != 0)
        print("yay!");
    }
));

This might be of use to you.
http://answers.unity3d.com/questions/744888/returning-an-ienumerator-as-an-int.html

Leave a Comment