Prefabs实例化 ResourceMgr

http://www.xiaobao1993.com/886.html

来源与小宝个人笔记【稍作修改】

//使用  Prefabs/Resources/stone1

ResourceMgr.GetInstance().CreateGameObject ("stone1",image,true);


using UnityEngine; using System.Collections; public class ResourceMgr : MonoBehaviour { #region 初始化 private static ResourceMgr mInstance; /// <summary> /// 获取资源加载实例 /// </summary> /// <returns></returns> public static ResourceMgr GetInstance() { if(mInstance == null) { mInstance = new GameObject("_ResourceMgr").AddComponent<ResourceMgr>(); } return mInstance; } private ResourceMgr() { Debug.LogError ("---------------"); hashtable = new Hashtable(); } #endregion /// <summary> 资源缓存容器 </summary> private Hashtable hashtable; /// <summary> /// Load 资源 /// </summary> /// <typeparam name="T">资源类型</typeparam> /// <param name="path">资源路径</param> /// <param name="cacheAsset">是否要缓存资源</param> /// <returns></returns> public T Load<T>(string path, bool cache) where T : Object { if (hashtable.Contains(path)) { return hashtable[path] as T; } Debug.Log(string.Format("Load assset frome resource folder,path:{0},cache:{1}", path, cache)); T assetObj = Resources.Load<T>(path); if (assetObj == null) { Debug.LogWarning("Resources中找不到资源:" + path); } if (cache) { hashtable.Add(path, assetObj); Debug.Log("Asset对象被缓存,Resource'path=" + path); } return assetObj; } /// <summary> /// 创建Resource中GameObject对象 /// </summary> /// <param name="path"资源路径</param> /// <param name="cacheAsset">是否要缓存Asset对象</param> /// <returns></returns> public GameObject CreateGameObject(string path,GameObject parent, bool cache) { GameObject assetObj = Load<GameObject>(path, cache); GameObject go = Instantiate(assetObj) as GameObject; if (go != null && parent != null) { Transform t = go.transform; t.parent = parent.transform; t.localPosition = Vector3.zero; t.localRotation = Quaternion.identity; t.localScale = Vector3.one; go.layer = parent.layer; } if (go == null) { Debug.LogWarning("从Resource创建对象失败:" + path); } return go; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }

  

posted on 2015-09-02 11:26  602147629  阅读(291)  评论(0编辑  收藏  举报