using UnityEngine; using System.Collections; using System.Collections.Generic; using Game; // 局部对象池模板 public class UnitPool where T : MonoBehaviour { private Transform mb_vParentTf; // 创建对象时的父节点 private string mb_vPrefabName; // 对象预制名称 private List mb_vObjList; // 对象列表 public int iActivityCount { get { int retCount = 0; if (mb_vObjList != null) { for (int i = 0; i < mb_vObjList.Count; i++) { if (mb_vObjList[i].gameObject.activeSelf) retCount++; } } return retCount; } } public List vObjList { get { if (mb_vObjList == null) mb_vObjList = new List(); return mb_vObjList; } } // 默认构造 需要配合 Init()使用 public UnitPool() { } // 构造 并 Init() public UnitPool(Transform tfParent) { string vPrefabName = typeof(T).FullName; this.Init(tfParent, vPrefabName); } // 构造 并 Init() public UnitPool(Transform tfParent, string vPrefabName) { this.Init(tfParent, vPrefabName); } // 初始化 public void Init(Transform tfParent, string vPrefabName) { mb_vParentTf = tfParent; mb_vPrefabName = vPrefabName; } // 隐藏 public void Hide() { for (int i = 0; i < vObjList.Count; i++) { vObjList[i].gameObject.SetActive(false); } } // 隐藏父节点 public void HideNode() { mb_vParentTf.gameObject.SetActive(false); } // 显示父节点 public void ShowNode() { mb_vParentTf.gameObject.SetActive(true); } // 获取 public T GetObj(int index) { if (index < vObjList.Count) { vObjList[index].gameObject.SetActive(true); return vObjList[index]; } string uiName = typeof(T).FullName; var strNameAry = uiName.Split('.'); uiName = strNameAry[strNameAry.Length - 1]; var uiPath = UIMgr.AllUIPath[uiName]; GameObject go = UIMgr.Instance.Clone(uiPath, mb_vParentTf); go.name = uiName; T vObj = go.GetComponent(); if(vObj == null) vObj = go.AddComponent(); vObjList.Add(vObj); return vObj; } // 获取 public T GetAnyHide() { int count = vObjList.Count; for (int i = 0; i < count; i++) { if (!vObjList[i].gameObject.activeSelf) { vObjList[i].gameObject.SetActive(true); return vObjList[i]; } } return GetObj(count); } public void Remove(int index) { if (index >= vObjList.Count) return; T vObj = vObjList[index]; GameObject.Destroy(vObj.gameObject); vObjList.RemoveAt(index); } public void Remove(T obj) { for (int i = 0; i < vObjList.Count; i++) { if (vObjList[i] == obj) { GameObject.Destroy(obj.gameObject); vObjList.RemoveAt(i); return; } } } // 销毁 public void Destory() { for (int i = 0; i < vObjList.Count; i++) { T vObj = vObjList[i]; GameObject.Destroy(vObj.gameObject); } vObjList.Clear(); } }