使用场景:在Unity中要从Resources文件夹加载资源时需要知道,资源的具体路径,有时遇到路径的更改十分麻烦。这个脚本可以实现通过名字直接load对应资源。
主要思想:在editor中做一个方法,实现将Resources文件夹中所有资源按一定的格式写入一个文档并将该文档存放在StreamingAssets文件夹下,便于在游戏运行过程中查找到该文档。
1、ResourcesManager:主要方法脚本
public class ResourceManager
{
//存放名字和路径
private static Dictionary<string,string> configMap;
//初始化类的静态数据成员
//类被加载时只执行一次
static ResourceManager()
{
string fileContent = GetConfigFile("ConfigMap.txt");
BuildMap(fileContent);
}
//根据存放在文档内的记录,提取出名字与路径存放在字典中
private static void BuildMap(string fileContent)
{
configMap = new Dictionary<string, string>();
using (StringReader stringReader = new StringReader(fileContent))
{
//当程序退出using代码块,将自动释放内存
string line;
while ((line = stringReader.ReadLine()) != null)
{
string[] keyValue = line.Split('=');
configMap.Add(keyValue[0], keyValue[1]);
}
}
}
//寻找存放着记录的文档
public static string GetConfigFile(string fileName)
{
//通过文档的名字生成路径并寻找
var url = new System.Uri(Path.Combine(Application.streamingAssetsPath, fileName));
UnityWebRequest request = UnityWebRequest.Get(url);
request.SendWebRequest();
if (request.error == null )
{
while (true)
{
//返回文档中的记录
if (request.downloadHandler.isDone)
{
return request.downloadHandler.text;
}
}
}
else
{
Debug.LogError("读取ConfigMap文件失败");
return string.Empty;
}
}
//对外提供通过名字,输出Resoures文件夹中资源的方法
public static T Load<T>(string name)where T : Object
{
string path = configMap[name];
return Resources.Load<T>(path);
}
}
2、GenerateResConfig(提供在unity编辑器界面中一键生成文档的editor方法)
//以editor为父类
public class GenerateResConfig : Editor
{
//调用方法的按键存放位置
[MenuItem("Tools/Resources/Generate ResConfig")]
//生成文档的方法
public static void Generate()
{
//生成资源配置文件
//(过滤器(t:后缀名),文件夹)
string[] resFiles = AssetDatabase.FindAssets("t:prefab", new string[] { "Assets/Resources" });
//找到的是资源id
for (int i = 0; i < resFiles.Length; i++)
{
//将找到的资源id改为路径
resFiles[i] = AssetDatabase.GUIDToAssetPath(resFiles[i]);
//根据一定的规定生成记录
string fileName = Path.GetFileNameWithoutExtension(resFiles[i]);
string filePath =resFiles[i].Replace("Assets/Resources/", string.Empty).Replace(".prefab", string.Empty);
resFiles[i] = fileName+"="+ filePath;
}
//将记录写入文档
File.WriteAllLines("Assets/StreamingAssets/ConfigMap.txt", resFiles);
//刷新,释放内存
AssetDatabase.Refresh();
}
}