using System.Collections.Generic; using UnityEngine; public class PoolManager : Singleton { private Dictionary>> _resourcePool; private List _useList; public PoolManager() { _resourcePool = new Dictionary>>(); _useList = new List(); } public List UseList { get => _useList; } /// /// 从对象池获取资源 /// /// 资源类型 /// 资源 id /// 资源对象 public GameObject GetResourceInFreePool(EResourceType type, int id) { GameObject tempObj = null; // 判断对象池是否有该类型对象 if (_resourcePool.ContainsKey(type)) { // 判断空闲对象池是否有该 id if (_resourcePool[type].ContainsKey(id)) { // 如果个数大于 0 if (_resourcePool[type][id].Count > 0) { tempObj = _resourcePool[type][id][0]; _resourcePool[type][id].Remove(tempObj); } } } // 没有则创建 if (null == tempObj) tempObj = NewResource(type, id); // 加入使用列表 UseList.Add(tempObj); tempObj.SetActive(true); return tempObj; } /// /// 回收所有资源 /// public void RecycleResource() { for (int i = UseList.Count - 1; i >= 0; i--) { RecycleResource(UseList[i]); } } /// /// 回收资源 /// /// 资源对象 public void RecycleResource(GameObject gameObject) { EResourceType type = EResourceType.Actor; if (gameObject.GetComponent()) type = EResourceType.Environment; else if (gameObject.GetComponent()) type = EResourceType.Item; else if (gameObject.GetComponent()) type = EResourceType.Actor; else if (gameObject.GetComponent()) { // 触发怪物死亡事件 if (gameObject.GetComponent().Health == 0) gameObject.GetComponent().OnDeath?.Invoke(); // 怪物需要重置生命值 type = EResourceType.Enemy; gameObject.GetComponent().Health = gameObject.GetComponent().MaxHealth; } else return; int id = gameObject.GetComponent().ID; // 判断对象池是否有该类型对象 if (_resourcePool.ContainsKey(type)) { // 判断对象池是否有该 id if (_resourcePool[type].ContainsKey(id)) _resourcePool[type][id].Add(gameObject); // 没有则增加 else { List tempList = new List(); tempList.Add(gameObject); _resourcePool[type].Add(id, tempList); } } // 没有则增加 else { Dictionary> tempDic = new Dictionary>(); List tempList = new List(); tempList.Add(gameObject); tempDic.Add(id, tempList); _resourcePool.Add(type, tempDic); } // 将物体从使用列表中删除 UseList.Remove(gameObject); // 将物体设置为禁用 gameObject.SetActive(false); } /// /// 创建资源 /// /// 对象类型 /// 对象 id /// 资源对象 private GameObject NewResource(EResourceType type, int id) { return GameManager.Instance.ResourceManager.LoadResource(type, id); } }