Unity LoadImageIntoTexture无效

时间:2016-06-02 21:12:00

标签: android image web unity3d textures

我有一些代码可以让我在Android设备中获取所有图像路径。然后,我想使用www类将这些图像加载到纹理中,例如:

public void SetImage()
{
    List<string> galleryImages = GetAllGalleryImagePaths();

    DebugText.text = galleryImages.Count.ToString() + " images found";

    DisplayPanel.SetActive(true);
    ControlPanel.SetActive(false);

    for (int i = 0; i < galleryImages.count; i++)
    {
        WWW www = new WWW(galleryImages[i]);

        Texture2D t = new Texture2D(2, 2);
        www.LoadImageIntoTexture(t);

        GameObject imgObj = Instantiate(Resources.Load("GalleryImage")) as GameObject;
        imgObj.GetComponent<RawImage>().texture = t;
        imgObj.transform.SetParent(contentHolder.transform);
    }
}

但是,如果我调用www.LoadImageIntoTexture(t)并循环太多次,应用程序将跳转到主屏幕。 (好几次,好像20次,很好)

任何人都知道问题以及如何解决它?

1 个答案:

答案 0 :(得分:1)

在继续之前,您不是在等待下载完成。您要么必须为要返回的WWW对象进行收益,要么手动检查它们是否已完成。

要让它作为协程运行,您可以将代码修改为

public IEnumerator SetImage()
{
    List<string> galleryImages = GetAllGalleryImagePaths();

    DebugText.text = galleryImages.Count.ToString() + " images found";

    DisplayPanel.SetActive(true);
    ControlPanel.SetActive(false);

    for (int i = 0; i < galleryImages.count; i++)
    {
        WWW www = new WWW(galleryImages[i]);
        yield return www; //Wait for the download to complete

        Texture2D t = new Texture2D(2, 2);
        www.LoadImageIntoTexture(t);

        GameObject imgObj = Instantiate(Resources.Load("GalleryImage")) as GameObject;
        imgObj.GetComponent<RawImage>().texture = t;
        imgObj.transform.SetParent(contentHolder.transform);
    }
}

或者检查每个WWW实例isDone