如何加载与XNA文件夹中的所有文件? [英] How to load all files in a folder with XNA?

查看:112
本文介绍了如何加载与XNA文件夹中的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要加载的所有文件夹中的使用内容/纹理进入游戏 Content.Load(文件名);

I want to load all files in a folder "Content/textures" into the game using Content.Load("filename");

不过,我无法去找,位于里面的内容这样的文件(程序,而着眼于斌/调试/../内容/纹理但我得到尝试与Content.Load有加载JPG / PNG文件时出错。

However, I am unable to "find" files located inside Content this way (the program rather looks at "bin/debug/../Content/textures", but I get an error when trying to load the jpg/png files there with Content.Load.

我如何能实现我想要做什么?
口想(其中内容的文件夹是正确的?)来加载所有的文件里面的内容的文件夹中进入游戏,让我不必指定每一个纹理。

How can I achieve what I'm trying to do? I want to load all files in a folder inside Content (which content folder is the right one?) into the game, so that I dont have to specify every single texture.

感谢。

推荐答案

您可以使用此辅助类来做到这一点。它的工作原理,采取一个给定的目录,并使用的GetFiles()方法来创建所需要要加载的所有纹理的清单,然后加载它们正常与 ContentManager ,并把它们变成一个字典,所以你可以使用它们。

You can use this helper class to do this. It works by taking a given directory and using the GetFiles() method to create a list of all the textures that are needed to be loaded. It then loads them as normal with your ContentManager, and puts them into a dictionary so you can use them.

 public static class TextureContent
    {
        public static Dictionary<string, T> LoadListContent<T>(this ContentManager contentManager, string contentFolder)
        {
            DirectoryInfo dir = new DirectoryInfo(contentManager.RootDirectory + "/" + contentFolder);
            if (!dir.Exists)
                throw new DirectoryNotFoundException();
            Dictionary<String, T> result = new Dictionary<String, T>();

            FileInfo[] files = dir.GetFiles("*.*");
            foreach (FileInfo file in files)
            {
                string key = Path.GetFileNameWithoutExtension(file.Name);


                result[key] = contentManager.Load<T>(contentFolder + "/" + key);
            }
            return result;
        }
    }



创建一个字典来存储纹理,而不是线字符串的Texture2D>的的Texture2D 取值

  public Dictionary<string, Texture2D> spriteContent;



...并调用该方法在 LoadContent

 spriteContent = TextureContent.LoadListContent<Texture2D>(content, "textures");

现在,每当你需要从它的质感,只是做:

Now whenever you need a texture from it, just do:

Whatever.Image = spriteContent["WhateverTexture"]

确认 TextureName 是纹理的资产名称。

Make sure the TextureName is the asset name of your texture.

这篇关于如何加载与XNA文件夹中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆