Tai Wu
Tai Wu

Reputation: 83

Unity LoadImageIntoTexture isn't working

I have some code that allows me to grab all my image paths in my Android device. Then, I want to load those images into texture using www classs, such as:

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

However, if I call www.LoadImageIntoTexture(t) and loop too many times, the app will just jump out to the home screen. (a few times, like 20 times, is fine)

Anyone knows the problem and how to fix it?

Upvotes: 0

Views: 619

Answers (1)

Bart
Bart

Reputation: 20028

You are not waiting for your downloads to finish before you move on. You either have to yield for the WWW objects to return, or manually check whether or not they are done.

To have it work as a coroutine, you can modify your code to

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

Either that, or check each WWWinstance for isDone.

Upvotes: 1

Related Questions