用WWW类加载多个外部纹理

本文关键字:外部 纹理 WWW 类加载 | 更新日期: 2023-09-27 18:08:12

我想在运行时使用Unity加载多个png文件。我使用www类加载给定目录的纹理。下面是我的代码:

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

这个函数被称为协程。当程序完成加载所有纹理时,textureList数组具有正确的纹理数量。但它们都是最后加载的纹理。

用WWW类加载多个外部纹理

你只使用一个对象犯了一个小错误:

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

Dr. Fre也在评论中说过

这里有个小错误:using (WWW www = new WWW("file://" + Path.GetFullPath(_path))) .

您应该使用foreach循环中的url,即fileDir

编辑:

也将textureList = new List<Texture2D>();移出函数。把它放到Start()函数或者别的什么里面。

    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);
                textureList.Add(texture);
            }
        }
    }

注意:建议在Unity中使用for循环而不是foreach循环来循环List。在Unity 5.5中你不需要担心这个