别人的代码
public enum ResourceType { UIScene, UIWindow, Role, Effect } private Hashtable m_PrefabTable; Dictionary<string, GameObject> dictionary; public SceneMgr() { dictionary = new Dictionary<string, GameObject>(); m_PrefabTable = new Hashtable(); }
public GameObject Load(ResourceType type, string path, bool cache = false) { GameObject obj = null; if (m_PrefabTable.Contains(path)) { obj = m_PrefabTable[path] as GameObject; } else { StringBuilder sbr = new StringBuilder(); switch (type) { case ResourceType.UIScene: sbr.Append("UIPrefabs/UIScene/"); break; case ResourceType.UIWindow: sbr.Append("UIPrefabs/UIWindows/"); break; case ResourceType.Role: sbr.Append("RolePrefab/"); break; case ResourceType.Effect: sbr.Append("EffectPrefab/"); break; } sbr.Append(path); obj = Resources.Load(sbr.ToString()) as GameObject; if (cache) { m_PrefabTable.Add(path, obj); } } return Object.Instantiate(obj); }
GameObject go; void Start () { go = SceneMgr.Instance.Load(SceneMgr.ResourceType.UIScene, "UI Root_LogOnScene",true); } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { go = SceneMgr.Instance.Load(SceneMgr.ResourceType.UIScene, "UI Root_LogOnScene", true); } if (Input.GetMouseButtonDown(1)) { Debug.Log(go); Destroy(go); } }
这个代码没什么问题. 只需要在需要生成物体的地方调用一下,传给一个枚举资源类型, 一个预设名字,和一个是否使用缓存的bool. , 我想用自己的方式实现了一下出了一些问题
细看:
public GameObject LoadResources(ResourceType type, string path, bool isCache = true) { StringBuilder sbr = new StringBuilder(); sbr.Append("UIPrefabs/" + type.ToString() + "/" + path); GameObject goTemp = null; if (isCache) { if (dictionary.TryGetValue(sbr.ToString(), out goTemp)) { Debug.Log("cache"); Object.Instantiate(goTemp); return goTemp; } } goTemp = Resources.Load(sbr.ToString()) as GameObject; Object.Instantiate(goTemp); dictionary.Add(sbr.ToString(), goTemp); Debug.Log("new"); return goTemp; }
只是修改了这个类,乍一看没什么不一样,只是改了一下枚举.tostring,节省了一些代码, 但是实际上不是这样的. 当我点击鼠标右键的时候. 报了有资源在使用对象,不能够Destory, 问题有了 找了找解决了更改为如下代码
1 public GameObject LoadResources(ResourceType type, string path, bool isCache = true) 2 { 3 4 StringBuilder sbr = new StringBuilder(); 5 6 sbr.Append("UIPrefabs/" + type.ToString() + "/" + path); 7 GameObject goTemp = null; 8 if (isCache) 9 { 10 11 if (dictionary.TryGetValue(sbr.ToString(), out goTemp)) 12 { 13 Debug.Log("cache"); 14 15 return Object.Instantiate(goTemp); 16 } 17 } 18 19 goTemp = Resources.Load(sbr.ToString()) as GameObject; 20 21 dictionary.Add(sbr.ToString(), goTemp); 22 Debug.Log("new"); 23 return Object.Instantiate(goTemp); 24 25 }
注意第15行和第23行, 这里就是区别 , 这里我猜测, 因为前边的代码是在这个类中生成的实例,而返回的是一个内存的克隆体, 在修改后直接将对象返回,就没有出现资源在占用不能删除这样的错误了. 还挺奇怪的, 在这里写一个记录,
Update: 又发现了一个问题, 就是如果第三个参数传的是false,那么会出现key重复的情况, 所以下边这种不可取, 还是使用上边的方式