每次加载物体都要去获得物体路径,然后在去加载,这样很不方便而且会出错。下面我把物体的名称和物体对应的路径读取到配置表里面,直接通过物体的名称去获得路径去加载物体。
一 配置表的制作
/*******************
* Title:CW_FrameWark
* Author:CW
* ScriptName: CreateResini
* Des:将资源的名称和路径对应
******************/
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
public class CreateResInit : MonoBehaviour {
[MenuItem("CW/CreateResInit")]
public static void CreateInit()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
string resPath = Application.dataPath + "/Resources/";
string initPath = resPath + "Res.txt";
if (File.Exists(initPath))
{
File.Delete(initPath);
}
CreateResInfo(resPath, ref dic);
List<string> list = new List<string>();
foreach (KeyValuePair<string,string > keyvalue in dic)
{
list.Add(keyvalue.Key + "=" + keyvalue.Value);
}
File.WriteAllLines(resPath + "/res.txt", list.ToArray());
Debug.Log("生成完毕 ");
AssetDatabase.Refresh();
}
public static void CreateResInfo(string path,ref Dictionary<string,string> dic)
{
DirectoryInfo dir = new DirectoryInfo(path);
if(!dir.Exists)
{
Debug.Log("path:"+ path+"is not exit");
return;
}
FileInfo[] files = dir.GetFiles();
for (int i = 0; i < files.Length; i++)
{
FileInfo fileInfo = files[i];
if(!(fileInfo.Name.IndexOf(".meta",0)>0))
{
string tmpPathDir = fileInfo.FullName.Replace("\\", "/")
.Replace((Application.dataPath + "/Resources/"), "");
string pathDir= tmpPathDir.Split('.')[0];
string fileName = Path.GetFileNameWithoutExtension(fileInfo.Name);
Debug.Log("fileName=" + fileName);
if(!dic.ContainsKey(fileInfo.Name))
{
dic.Add(fileName, pathDir);
}
else
{
Debug.LogError ("存在相同的资源名称 名称为:" + fileInfo.Name + "/path1=" + dic[fileInfo.Name] + "/ path2 =" + pathDir);
}
}
}
DirectoryInfo[] dirs = dir.GetDirectories();
if(dirs.Length>0)
{
for (int i = 0; i < dirs.Length; i++)
{
string tmpPath = Path.Combine(path,dirs[i].Name);
CreateResInfo(tmpPath, ref dic);
}
}
}
}
2 测试根据物体名称去加载游戏物体
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
public class TestLoad : MonoBehaviour {
private Dictionary<string ,string> _resInitDic=new Dictionary<string, string>();
void Start()
{
ReadResInit();
foreach(KeyValuePair<string,string> kv in _resInitDic)
{
Debug.Log(kv.Key+"=="+kv.Value);
}
}
void Update()
{
if(Input.GetKeyDown(KeyCode.W))
{
Instantiate(Resources.Load(_resInitDic["Cube"]));
}
}
private void ReadResInit()
{
TextAsset txt=Resources.Load("res") as TextAsset;
byte[] array = Encoding.ASCII.GetBytes(txt.text);
MemoryStream memoryStream=new MemoryStream(array);
StreamReader streamReader=new StreamReader(memoryStream);
string line= streamReader.ReadLine();
while(!string.IsNullOrEmpty(line))
{ Debug.Log(line);
string[] arrys=line.Split('=');
_resInitDic.Add(arrys[0],arrys[1]);
line= streamReader.ReadLine();
}
}
}