C# 使用WWW类加载多个外部纹理
我想在运行时使用Unity加载多个png文件。我使用www类加载给定目录下的纹理。这是我的密码:C# 使用WWW类加载多个外部纹理,c#,unity3d,textures,ienumerator,C#,Unity3d,Textures,Ienumerator,我想在运行时使用Unity加载多个png文件。我使用www类加载给定目录下的纹理。这是我的密码: public IEnumerator LoadPNG(string _path) { string[] filePaths = Directory.GetFiles(_path); foreach (string fileDir in filePaths) { using (WWW www = new 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=newwww(“file://”+Path.GetFullPath(\u Path))
您应该使用foreach
循环中的url
,即fileDir
编辑:
同时移动textureList=newlist()代码>在函数外部。把它放在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);
}
}
}
注意:建议使用for
循环来循环列表
,而不是统一的foreach
循环。在Unity 5.5中,您不必担心这个问题。您只使用了一个对象,犯了一个小错误:
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);
}
正如弗雷博士在评论中所说的那样。使用这一行(Texture2D texture=Texture2D.whiteTexture;),您总是将引用设置为同一对象。你必须初始化一个新的纹理。我认为有了(新的纹理2D)它就可以工作了。如果没有资源,你不能直接在unity中说新的纹理2D。我已经通过LoadImageIntoTexture写入了纹理变量。所以我认为这应该不是问题。@mcelik您可以将new
关键字与Texture2D
一起使用,我认为这是您的问题,因为您更新了代码<代码>纹理2D纹理=新纹理2D(4,4,TextureFormat.DXT1,false)代码>你们都是对的。对不起,我没有足够的知识就直接回答了。使用新的纹理2D解决了这个问题。但我不明白它为什么起作用?我的错。我的工作代码是使用fileDir。但在问题中写错了:/现在编辑了。@mcelik看编辑。MovetextureList=new Dictionary()代码>在LoadPNG
函数之外。另外,我认为你的问题中还有一个拼写错误。不是textureList=newdictionary()代码>假设为textureList=new List()代码>?如果没有,则textureList.Add(纹理)代码>不应编译。请在您的问题中解决此问题…始终尝试按原样放置您的代码,以防止问题中出现类似问题。最新编辑的代码版本将更清楚地反映问题。谢谢。根据他问题中的当前代码,这是解决方案。对,这是解决方案。谢谢大家。