我必须从网址加载图片时遇到麻烦。我从POST到服务器的响应中获取此URL。
所以我有以下的POST功能:
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");
}
}
我不知道为什么,但是当我这样做时,图像/视频不会显示..因为渲染代码在请求函数中?我测试时无需POST,我只是对网址进行了硬编码和工作。
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;
}
}
答案 0 :(得分:2)
GameObject plno = GameObject.Find ("Plane").gameObject;
LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
planeScript.url = jsonData[i].url;
您分配了网址,现在您必须从LoadImageFromUrl组件调用下载协同程序。将您的课程改为:
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;
}
}
并添加
planeScript.Download()
之后
planeScript.url = jsonData[i].url;
与视频相同