/******************************************************************** 文件: PoolManager.cs 作者: 梦语 邮箱: 1982614048@qq.com 创建时间: 2024/03/29 17:28:19 最后修改: 梦语 最后修改时间: 2024/04/12 17:56:30 功能: 对象池管理类 *********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Ether { public class PoolManager : SingletonAutoMono { private Dictionary objectPoolDic = new Dictionary(); private Dictionary gameObjectPoolDic = new Dictionary(); #region object /// /// 放入对象池 /// /// public void Push(object obj) { string name = obj.GetType().FullName; if (!objectPoolDic.ContainsKey(name)) { objectPoolDic.Add(name, new ObjectPool()); } objectPoolDic[name].Push(obj); } /// /// 从对象池中获取 /// /// /// 对应的对象 public T Get() where T : new() { string name = typeof(T).FullName; if (objectPoolDic.ContainsKey(name)) { return objectPoolDic[name].Get(); } else { return new T(); } } public object Get(string typeName) { Type type = CommonTools.GetType(typeName); return Get(type); } public object Get(Type type) { string name = type.FullName; if (objectPoolDic.ContainsKey(name)) { return objectPoolDic[name].Get(type); } else { return Activator.CreateInstance(type); } } /// /// 获取对象池中的数量 /// /// /// public int GetCount() where T : new() { string name = typeof(T).FullName; if (!objectPoolDic.ContainsKey(name)) { return 0; } return objectPoolDic[name].GetCount(); } #endregion #region GameObject /// /// 放入对象池 /// /// public void Push(GameObject obj, string name = "") { name = string.IsNullOrEmpty(name) ? obj.GetType().FullName : name; if (!gameObjectPoolDic.ContainsKey(name)) { gameObjectPoolDic.Add(name, new GameObjectPool(name, gameObject)); } gameObjectPoolDic[name].Push(obj); } /// /// 从对象池中获取 /// /// /// /// 对应的GameObject实例对象 public GameObject Get(string assetName, Transform parent = null) { if (!gameObjectPoolDic.ContainsKey(assetName)) { gameObjectPoolDic.Add(assetName, new GameObjectPool(name, gameObject)); } return gameObjectPoolDic[assetName].Get(assetName, parent); } /// /// 从对象池中获取 /// /// /// /// 对应的GameObject实例对象 public GameObject Get(GameObject assetGo, Transform parent = null) { string assetName = assetGo.name; if (!gameObjectPoolDic.ContainsKey(assetName)) { gameObjectPoolDic.Add(assetName, new GameObjectPool(name, gameObject)); } return gameObjectPoolDic[assetName].Get(assetGo, parent); } /// /// 获取对象池中的数量 /// /// /// public int GetCount(string assetName) { if (!objectPoolDic.ContainsKey(assetName)) { return 0; } return objectPoolDic[assetName].GetCount(); } #endregion /// /// 清理 /// public override void Clear() { objectPoolDic.Clear(); for (int i = 0; i < gameObject.transform.childCount; i++) { Destroy(gameObject.transform.GetChild(i)); } gameObjectPoolDic.Clear(); } } }