How can I display text from a webrequest?
I am using a HTTP request to try and access a REST endpoint. I want to display the text I get in a canvas but I can't seem to get the output of the request to display in the Canvas.
using UnityEngine.Networking;
class Rest_test : MonoBehaviour {
public TextMesh thistext;
// Use this for initialization
void Start () {
StartCoroutine (GetText ());
}
IEnumerator GetText() {
UnityWebRequest www = UnityWebRequest.Get("http://jsonplaceholder.typicode.com/posts/1");
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.Send();
if(www.isError) {
Debug.Log(www.error);
}
else {
// Show results as text
Debug.Log(www.downloadHandler.text);
// Or retrieve results as binary data
//byte[] results = www.downloadHandler.data;
}
}
void Update () {
thistext.text = GetText ();
}
}
I'm pretty new to C# and Unity so i may be missing something very basic. I get the following error when I add the script to my scene: Assets/Rest_test.cs(30,18): error CS0029: Cannot implicitly convert type System.Collections.IEnumerator' to
string'
your Update method is trying to assign the IEnumerator of GetText() to text and that won't work. Delete the whole Update method and assign the text where you have the Debug.Log reading that out
Thanks - it now looks like this:
else {
// Show results as text
Debug.Log(www.downloadHandler.text);
thistext.text = www.downloadHandler.text;
}
But I get a warning that "Field Rest_test.thistext' is never assigned to, and will always have its default value
null'" so my canvas does not get updated. I'm obviously still doing something wrong...
the warning is fine. the compiler just doesn't know that the field gets injected.
the question is, do you even reach that part of the code?
Answer by aFeesh · Mar 03, 2018 at 05:36 PM
You want to use www.downloadHandler.text and not overwrite the downloadHandler with a new instance. You may also want to use www.SendWebRequest() instead of www.Send()
IEnumerator GetText() {
UnityWebRequest www = UnityWebRequest.Get("http://jsonplaceholder.typicode.com/posts/1");
yield return www.SendWebRequest();
if (www.isError) {
Debug.Log(www.error);
} else {
// Show results as text
Debug.Log(www.downloadHandler.text);
// Or retrieve results as binary data
//byte[] results = www.downloadHandler.data;
}
}
Answer by toddisarockstar · Mar 31, 2017 at 11:58 PM
this is how i usually do it:
using UnityEngine;
using System.Collections;
public class wwww : MonoBehaviour {
WWW www;
string txt;
bool gotit;
byte[] bytes;
void Start () {
www = new WWW("http://jsonplaceholder.typicode.com/posts/1");
}
void Update () {
if (!gotit){
if (www.isDone) {gotit=true;
if(www.error==null){
bytes=www.bytes;
txt = www.text;
print (txt);
print ("i got "+bytes.Length+" bytes from download");
}else{print("I got this error: "+www.error);}
}
}
Thanks - this does work but I was hoping to use the newer UnityWebrequest.