Bạn có thể sử dụng helper này lớp để làm điều này. Nó hoạt động bằng cách lấy một thư mục nhất định và sử dụng phương thức GetFiles()
để tạo danh sách tất cả các kết cấu cần thiết để nạp. Sau đó tải chúng như bình thường với ContentManager
và đặt chúng vào từ điển để bạn có thể sử dụng chúng.
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;
}
}
Tạo một từ điển để lưu trữ các kết cấu, chứ không phải là từng dòng Texture2D
s
public Dictionary<string, Texture2D> spriteContent;
...Và gọi phương thức trong LoadContent
phương pháp của bạn
spriteContent = TextureContent.LoadListContent<Texture2D>(content, "textures");
Bây giờ bất cứ khi nào bạn cần một kết cấu từ nó, chỉ cần làm:
Whatever.Image = spriteContent["WhateverTexture"]
Hãy chắc chắn rằng TextureName
là tên nội dung của kết cấu của bạn.