Search code examples
c#unity-game-enginetexturesienumerator

Load multiple external textures with WWW class


I want to load multiple png files at runtime using Unity. I am using www class to load the textures with given directory. Here is my code:

    public IEnumerator LoadPNG(string _path)
    {
        string[] filePaths = Directory.GetFiles(_path);
        foreach (string fileDir in filePaths)
        {
            using (WWW www = new WWW("file://" + Path.GetFullPath(fileDir )))
            {
                yield return www;
                Texture2D texture = Texture2D.whiteTexture;
                www.LoadImageIntoTexture(texture);
                this.textureList.Add(texture);
            }
        }
    }

This function is called as coroutine. When the program finish the loading all textures, textureList array has correct amount of textures. But all of them are last loaded texture. Any help is appreciated.


Solution

  • You were doing small mistake with using only one object:

                using (WWW www = new WWW("file://" + Path.GetFullPath(fileDir )))
                {
                    yield return www;
                    // Change this...
                    //Texture2D texture = Texture2D.whiteTexture;
                    // to this:
                    Texture2D texture = new Texture2D(0, 0);
                    //or us this:
                    //Texture2D texture = www.texture;
                    www.LoadImageIntoTexture(texture);
                    textureList.Add(texture);
                }
    

    As Dr. Fre also stated in comments.