1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Events;
    5. /// <summary>
    6. /// 抽屉数据 池子中的一列容器
    7. /// </summary>
    8. public class PoolData
    9. {
    10. // 抽屉中 对象挂载的父节点
    11. public GameObject fatherObj;
    12. // 对象的容器
    13. public List<GameObject> poolList;
    14. public PoolData(GameObject obj, GameObject poolObj)
    15. {
    16. // 给抽屉创建一个父对象 并且把它作为pool对象的子物体
    17. fatherObj = new GameObject(obj.name);
    18. fatherObj.transform.parent = poolObj.transform;
    19. poolList = new List<GameObject>(){};
    20. PushObj(obj);
    21. }
    22. /// <summary>
    23. /// 往抽屉里压东西
    24. /// </summary>
    25. /// <param name="obj"></param>
    26. public void PushObj(GameObject obj)
    27. {
    28. // 存起来
    29. poolList.Add(obj);
    30. // 设置父对象
    31. obj.transform.parent = fatherObj.transform;
    32. // 失活 隐藏
    33. obj.SetActive(false);
    34. }
    35. /// <summary>
    36. /// 从抽屉里面取东西
    37. /// </summary>
    38. /// <returns></returns>
    39. public GameObject GetObj()
    40. {
    41. GameObject obj = null;
    42. // 取出第一个
    43. obj = poolList[0];
    44. poolList.RemoveAt(0);
    45. obj.SetActive(true);
    46. obj.transform.parent = null;
    47. return obj;
    48. }
    49. }
    50. /// <summary>
    51. /// 缓存池模块
    52. /// </summary>
    53. public class PoolMgr : BaseManager<PoolMgr>
    54. {
    55. // 缓存池容器
    56. public Dictionary<string, PoolData> poolDic = new Dictionary<string, PoolData>();
    57. private GameObject poolObj;
    58. /// <summary>
    59. /// 往外拿东西
    60. /// </summary>
    61. public void GetObj(string name, UnityAction<GameObject> CallBack)
    62. {
    63. //GameObject obj = null;
    64. // 有抽屉, 并且抽屉里有东西
    65. if (poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
    66. {
    67. //obj = poolDic[name].GetObj();
    68. CallBack(poolDic[name].GetObj());
    69. }
    70. else
    71. {
    72. // 通过异步加载obj
    73. ResMgr.GetInstance().LoadAsync<GameObject>(name, (o) =>
    74. {
    75. o.name = name;
    76. CallBack(o);
    77. });
    78. //obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
    79. //// 把对象名该为和池子名一样
    80. //obj.name = name;
    81. }
    82. }
    83. /// <summary>
    84. /// 还暂时不用的东西给我
    85. /// </summary>
    86. public void PushObj(string name, GameObject obj)
    87. {
    88. if (poolObj == null)
    89. poolObj = new GameObject("Pool");
    90. // 里面有抽屉
    91. if (poolDic.ContainsKey(name))
    92. {
    93. poolDic[name].PushObj(obj);
    94. }
    95. // 里面没有抽屉
    96. else
    97. {
    98. poolDic.Add(name,new PoolData(obj,poolObj));
    99. }
    100. }
    101. /// <summary>
    102. /// 清空缓存池, 主要用在场景切换时
    103. /// </summary>
    104. public void Clear()
    105. {
    106. poolDic.Clear();
    107. poolObj = null;
    108. }
    109. }