Unity对象池继续优化【资源加载方式改为异步】
1、优化点:
a、资源加载方式改为异步
b、添加资源加载完成的回调函数
c、对象池数据类获取对象方法添加设置父对象
2、具体实现:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; /// <summary> /// 对象池 缓存池 /// </summary> public class PoolManager : SingletonBase<PoolManager> { //对象池 类型名字/类型列表 public Dictionary<string, PoolData> poolDict = new Dictionary<string, PoolData>(); //对象池 父类对象 public GameObject poolParentObj; //游戏物体 父类 public GameObject thingParentObj; public void GetObj(string name,UnityAction<GameObject> callBack=null) { if (thingParentObj == null) thingParentObj = new GameObject("Things"); if (poolDict.ContainsKey(name) && poolDict[name].poolList.Count>0) { GameObject obj = poolDict[name].GetObj(thingParentObj); if(callBack!=null) callBack(obj); } else { ////对象池里没有对象时,实例化生成该对象 //通过异步加载 创建对象给外部使用 ResController.GetInstance().LoadAssetAsync<GameObject>(name, (o) => { o.name = name; o.transform.parent = thingParentObj.transform;//设置游戏父类对象 o.SetActive(true);//显示对象 if(callBack!=null) callBack(o); }); } } public void PushObj(string name, GameObject obj) { if (poolParentObj == null) poolParentObj = new GameObject("Pool"); if (poolDict.ContainsKey(name)) { poolDict[name].PushObj(obj,poolParentObj);//对象池里有该类型列表,直接在该列表添加 } else { poolDict.Add(name, new PoolData(name,obj,poolParentObj));//对象池里没有该类型列表 } } /// <summary> /// 清空对象池、格式化 /// 主要用于场景跳转,需要重置数据 /// </summary> public void Clear() { poolDict.Clear(); poolParentObj = null; thingParentObj = null; } } /// <summary> /// 对象池 数据类 /// </summary> public class PoolData { //抽屉列表 public List<GameObject> poolList; //抽屉名称 public string poolName; public PoolData(string name,GameObject obj,GameObject parObj) { poolList = new List<GameObject>();//实例化 该类型的对象列表 poolName = name;//保存 列表名字 obj.transform.parent = parObj.transform;//设置父对象 obj.SetActive(false);//设置不显示 } /// <summary> /// 从抽屉里 获得 衣服对象[默认取出第一个] /// </summary> /// <returns></returns> public GameObject GetObj(GameObject parentObj) { GameObject obj = poolList[0];//取出第一个 poolList.RemoveAt(0);//列表移除 obj.transform.parent = parentObj.transform;//设置父对象 obj.SetActive(true);//设置对象显示 return obj; } /// <summary> /// 将要回收的对象 添加至 对象池列表 /// </summary> /// <param name="obj">目标对象</param> /// <param name="poolParentObj">父类对象</param> public void PushObj(GameObject obj,GameObject poolParentObj) { obj.transform.parent = poolParentObj.transform; obj.SetActive(false); poolList.Add(obj); } }
测试:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameStart : MonoBehaviour { void Update() { if (Input.GetMouseButtonDown(0)) { PoolManager.GetInstance().GetObj("Pool/Cube", (obj) => { obj.transform.localScale = Vector3.one * 2; });//获得对象,生成显示 } if (Input.GetMouseButtonDown(1)) { PoolManager.GetInstance().GetObj("Pool/Cube2"); } } }
评论