Reputation: 2953
I have some code to get some data from a database. To use in my game. I have setup an coroutine to get this data with the WWW framework in unity. But when i run my code the data is never logged in my yield return function. Why is this happening? See the code below for the points that are not working:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Main : MonoBehaviour {
void Start () {
Debug.Log("run ma routine");
StartCoroutine(GetText("http://localhost/artez/praktijk_opdracht/interface_v4/app/php/get_fashion.php", (result) =>{
Debug.Log(result); // this log function is never logging a value.. Why is this?
}));
}
void Update ()
{
}
IEnumerator GetText(string url, Action<string> result) {
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
Debug.Log(www.downloadHandler.data); // this log is returning the requested data.
}
}
}
What i want is the StartCoroutine()
to log the data not the debug.log
inside of the IEnumerator()
If something needs more explanation i am happy to provide that.
Upvotes: 3
Views: 8872
Reputation: 125455
You have to invoke the result Action
after the UnityWebRequest
request is done inside the GetText
function:
if (result != null)
result(www.downloadHandler.text);
The new GetText
function:
IEnumerator GetText(string url, Action<string> result)
{
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
if (result != null)
result(www.error);
}
else
{
Debug.Log(www.downloadHandler.data); // this log is returning the requested data.
if (result != null)
result(www.downloadHandler.text);
}
}
Upvotes: 3