Question by
puchingeralexander · Jun 11, 2019 at 08:41 AM ·
unity 5webrequesthttpwebrequest
Finish UnityWebRequest before going further in Code
Hello people! The last few days i struggled with the following problem: my output should look like this -> First Log, Second Log some response data, Third log
But in fact it always looks like this -> First Log, Third Log, Second Log some response data
I have litteraly searched the whole internet but i didnt found a solution. Can anyone help me please? :)
Best regards Alex
using UnityEngine;
using System.Collections;
using UnityEngine.Experimental.Networking;
using UnityEngine.Networking;
public class Test : MonoBehaviour {
void Start()
{
Debug.Log("First Log");
StartCoroutine(GetText());
Debug.Log("Third Log");
}
IEnumerator GetText()
{
string url = "some url";
UnityWebRequest www = UnityWebRequest.Post(url,"some Data");
yield return www.SendWebRequest();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
// Show results as text
Debug.Log("Second Log: " + www.downloadHandler.text);
// Or retrieve results as binary data
//byte[] results = www.downloadHandler.data;
// Debug.Log(results);
}
}
}
Comment
Best Answer
Answer by Hellium · Jun 11, 2019 at 09:51 AM
Because coroutines are aynchronous, you have two possibilities :
1°) Create another coroutine responsible for outputting the First and Third log, and waiting for the GetText
coroutine to finish
void Start()
{
StartCoroutine(Foo());
}
IEnumerator Foo()
{
Debug.Log("First Log");
yield return StartCoroutine(GetText());
Debug.Log("Third Log");
}
IEnumerator GetText()
{
string url = "some url";
UnityWebRequest www = UnityWebRequest.Post(url,"some Data");
yield return www.SendWebRequest();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
// Show results as text
Debug.Log("Second Log: " + www.downloadHandler.text);
// Or retrieve results as binary data
//byte[] results = www.downloadHandler.data;
// Debug.Log(results);
}
}
2°) Use a callback function called by the coroutine when it ends
void Start()
{
Debug.Log("First Log");
StartCoroutine(GetText( OnTextRetrieved ));
}
void OnTextRetrieved()
{
Debug.Log("Third Log");
}
IEnumerator GetText( System.Action callback )
{
string url = "some url";
UnityWebRequest www = UnityWebRequest.Post(url,"some Data");
yield return www.SendWebRequest();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
// Show results as text
Debug.Log("Second Log: " + www.downloadHandler.text);
// Or retrieve results as binary data
//byte[] results = www.downloadHandler.data;
// Debug.Log(results);
if( callback != null )
callback();
}
}