微信登录

PoolManager.cs - 缓存池

PoolManager.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5. public class PoolData
  6. {
  7. //抽屉中的父对象
  8. public GameObject fatherObj;
  9. //对象中的容器
  10. public List<GameObject> poolList;
  11. public PoolData(GameObject obj,GameObject poolObj)
  12. {
  13. //给我们的抽屉 创建父对象 并且把他作为我们pool衣柜对象的子物体
  14. fatherObj = new GameObject(obj.name);
  15. fatherObj.transform.parent = poolObj.transform;
  16. poolList = new List<GameObject>() { };
  17. PushObj(obj);
  18. }
  19. //往抽屉里压东西
  20. public void PushObj(GameObject obj)
  21. {
  22. obj.SetActive(false);//失活 让其隐藏
  23. poolList.Add(obj);//存起来
  24. obj.transform.parent = fatherObj.transform;//设置父对象
  25. }
  26. //往抽屉里取东西
  27. public GameObject GetObj()
  28. {
  29. GameObject obj = null;
  30. //取出第一个
  31. obj = poolList[0];
  32. poolList.RemoveAt(0);
  33. obj.SetActive(true);//激活让其显示
  34. obj.transform.parent = null;//断开父子关系
  35. return obj;
  36. }
  37. }
  38. public class PoolManager : BaseManager<PoolManager>
  39. {
  40. public Dictionary<string, PoolData> poolDict = new Dictionary<string, PoolData>();
  41. public GameObject poolObj;
  42. /// <summary>
  43. /// 拿东西,出
  44. /// </summary>
  45. /// <param name="name"></param>
  46. /// <returns></returns>
  47. public void GetObj(string name,UnityAction<GameObject> callback = null)
  48. {
  49. //有物
  50. if(poolDict.ContainsKey(name) && poolDict[name].poolList.Count > 0)
  51. {
  52. callback(poolDict[name].GetObj());
  53. }
  54. //无物
  55. else
  56. {
  57. //旧,同步加载
  58. //obj = GameObject.Instantiate(Resources.Load<GameObject>(name));//新加载物体
  59. //obj.name = name;
  60. //新,异步加载
  61. ResourcesManager.GetInstance().LoadAsync<GameObject>(name, (o) =>
  62. {
  63. o.name = name;
  64. callback(o);
  65. });
  66. }
  67. }
  68. /// <summary>
  69. /// 放东西,入
  70. /// </summary>
  71. /// <param name="name"></param>
  72. /// <param name="obj"></param>
  73. public void PushObj(string name, GameObject obj)
  74. {
  75. //物体归类,同物体到同文件夹
  76. if (poolObj == null)
  77. poolObj = new GameObject("pool");
  78. //有类型
  79. if (poolDict.ContainsKey(name))
  80. {
  81. poolDict[name].PushObj(obj);
  82. }
  83. //无类型,新增类型
  84. else
  85. {
  86. poolDict.Add(name, new PoolData(obj,poolObj));
  87. }
  88. }
  89. /// <summary>
  90. /// 过场景的时候清空
  91. /// </summary>
  92. public void Clear()
  93. {
  94. poolDict.Clear();
  95. poolObj = null;
  96. }
  97. }