Reputation: 445
I'm having troubles when I have to Load image from url. I get this url on a response from a POST to server.
So I have the POST funtion below:
public void getDataStruct()
{
string url = " myurl";
WWWForm form = new WWWForm();
form.AddField("id", "2");
WWW www = new WWW(url, form);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Data[] jsonData = JsonHelper.FromJson<Data>(www.text);
for (int i = 0; i < jsonData.Length; i++)
{
switch(jsonData[i].tipo)
{
//Image
case 0:
GameObject plno = GameObject.Find ("Plane").gameObject;
LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
planeScript.url = jsonData[i].url;
break;
//video
case 1:
GameObject video = GameObject.Find ("Video1").gameObject;
VideoPlaybackBehaviour videocript = (VideoPlaybackBehaviour)video.GetComponent(typeof(VideoPlaybackBehaviour));
videocript.youtubeVideoIdOrUrl=jsonData[i].url;
break;
case 2:
break;
}
}
}
else {
MobileNativeMessage msg = new MobileNativeMessage("Error", "Error");
}
}
I don't know why but when I do this the image/video don't show..its because that render code is inside the request function? I tested without having to POST and I just hardcoded the urls and works.
the LoadFunction:
public class LoadImageFromUrl : MonoBehaviour {
public string url;
// Use this for initialization
IEnumerator Start () {
Texture2D tex;
tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
WWW www = new WWW(url);
yield return www;
www.LoadImageIntoTexture(tex);
GetComponent<Renderer>().material.mainTexture = tex;
}
}
Upvotes: 0
Views: 229
Reputation: 940
GameObject plno = GameObject.Find ("Plane").gameObject;
LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
planeScript.url = jsonData[i].url;
You assign the url, now you must call download coroutine from LoadImageFromUrl component. Change your class to something like this:
public class LoadImageFromUrl : MonoBehaviour {
public string url;
public void Download()
{
StartCoroutine(DownloadRoutine());
}
// Use this for initialization
IEnumerator DownloadRoutine () {
Texture2D tex;
tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
WWW www = new WWW(url);
yield return www;
www.LoadImageIntoTexture(tex);
GetComponent<Renderer>().material.mainTexture = tex;
}
}
And add
planeScript.Download()
after
planeScript.url = jsonData[i].url;
Same with video
Upvotes: 2