0

当我必须从 url 加载图像时,我遇到了麻烦。我在从 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");
    }  
}    

我不知道为什么,但是当我这样做时,图像/视频不显示..它是因为渲染代码在请求函数中?我无需发布即可进行测试,我只是对网址进行了硬编码并可以正常工作。

加载函数:

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;
    }
}
4

1 回答 1

2
GameObject plno = GameObject.Find ("Plane").gameObject;
            LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
            planeScript.url = jsonData[i].url;

您分配了 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;

和视频一样

于 2017-03-30T20:58:29.497 回答