Eugene Eugene - 3 months ago 16
C# Question

The order of command execution in Unity 5 using StartCoroutine / yield return www

There are 2 c# scripts, attached to the same game object (Unity 5.4)

public class SignIn : MonoBehaviour
{
private SendRequest sendRequest;

void Start()
{
sendRequest = GetComponent<SendRequest>();
}

public void signInPressed()
{
WWWForm form = new WWWForm();
form.AddField("key", "value");

sendRequest.POST(mainSettings.appUrl, form);

Debug.Log("SIGNIN");
}
}


and

public class SendRequest : MonoBehaviour {

public WWW POST(string url, WWWForm form)
{
WWW www = new WWW(url, form);

StartCoroutine(WaitForRequest(www));
return www;
}

private IEnumerator WaitForRequest(WWW www)
{
yield return www;

if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.text);
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
}


When I try to execute these scripts first displayed line SIGNIN, and then the server response.

How to get a response from the server first, and then continue the program?
What I'm doing wrong?

Answer

Have a look here :

StartCoroutine(WaitForRequest(www));
return www;

your method returns www object without waiting for WaitForRequest(www) to finish. If you are not using www returned from POST() method why do you return it.

How to work around it:

pass a delegate parameter to fire when coroutine is finished.

for example:

sendRequest.POST(mainSettings.appUrl, form, () => { Debug.Log("SIGNIN");});

and definition of POST():

public WWW POST(string url, WWWForm form, Action callback = null)
{
    WWW www = new WWW(url, form);

    StartCoroutine(WaitForRequest(www, callback));
}

and definition of WaitForRequest():

private IEnumerator WaitForRequest(WWW www, Action callback = null)
{
    yield return www;

    if (www.error == null)
    {
        Debug.Log("WWW Ok!: " + www.text);
    }
    else
    {
        Debug.Log("WWW Error: " + www.error);
    }

    if(callback != null)
    {
        callback();
    }
}

Hope it helps

Comments