【问题标题】:Load multiple external textures with WWW class使用 WWW 类加载多个外部纹理
【发布时间】:2016-09-21 14:56:13
【问题描述】:

我想在运行时使用 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 数组具有正确数量的纹理。但所有这些都是最后加载的纹理。任何帮助表示赞赏。

【问题讨论】:

  • 使用这条线 (Texture2D texture = Texture2D.whiteTexture;) 你总是将你的引用设置为同一个对象。你必须初始化一个新的纹理。我认为(新的 Texture2D)它会起作用
  • 没有资源就不能直接统一说new Texture2D。我已经通过 LoadImageIntoTexture 纹理覆盖了纹理变量。所以我认为这应该不是问题。
  • @mcelik 您可以将new 关键字与Texture2D 一起使用,我认为这是您的问题,因为您更新了代码。 Texture2D texture = new Texture2D(4, 4, TextureFormat.DXT1, false);
  • 你们俩都是对的。抱歉,我在没有足够知识的情况下跳入了答案。使用新的 Texture2D 解决了这个问题。但我不明白为什么它会起作用?

标签: c# unity3d textures ienumerator


【解决方案1】:

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

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

正如 Fre 博士在 cmets 中所说的那样。

【讨论】:

  • 现在他的问题中有当前代码,这就是解决方案。
  • 对,这就是解决方案。谢谢大家。
【解决方案2】:

这里的简单错误: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 中您不必担心这一点。

【讨论】:

  • 我的错误。我的工作代码正在使用 fileDir。但是在问题中写错了:/现在正在编辑。
  • @mcelik 查看编辑。将textureList = new Dictionary<Texture2D>(); 移到LoadPNG 函数之外。另外,我认为您的问题中还有另一个错字。 textureList = new Dictionary<int, Texture2D>(); 不应该是textureList = new List<Texture2D>(); 吗?如果不是,则 textureList.Add(texture); 不应编译。请在您的问题中解决这个问题....始终尝试按原样放置您的代码,以防止在您的问题中出现此类问题。
  • 代码的最新编辑版本会更清楚的问题。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2019-01-26
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
相关资源
最近更新 更多