1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4
5 /// <summary>
6 /// 抽屉数据 池子一列容器
7 /// </summary>
8 public class poolData
9 {
10 //抽屉中对象挂载的父节点
11 public GameObject fatherObj;
12 //对象的容器
13 public List<GameObject> poolList;
14
15
16 public poolData(GameObject obj,GameObject poolObj)
17 {
18 //给我们的抽屉 创建一个父对象,并且把他作为我们Pool(衣柜)对象的子物体
19 fatherObj = new GameObject(obj.name);
20 fatherObj.transform.parent = poolObj.transform;
21 poolList = new List<GameObject>() { };
22 PushObj(obj);
23 }
24
25
26 /// <summary>
27 /// 往抽屉里面,压东西
28 ///
29 /// </summary>
30 /// <param name="obj"></param>
31 public void PushObj(GameObject obj)
32 {
33 //东西放进来了,要把他失活,让其隐藏
34 obj.SetActive(false);
35 //存起来
36 poolList.Add(obj);
37 //设置父对象
38 obj.transform.parent = fatherObj.transform;
39
40 }
41
42 /// <summary>
43 /// 从抽屉里面取东西
44 ///
45 /// </summary>
46 /// <returns></returns>
47 public GameObject GetObj()
48 {
49 GameObject obj = null;
50
51
52 obj = poolList[0];
53 poolList.RemoveAt(0);
54
55 //断开父子联系
56 obj.transform.parent = null;
57 //取出东西的时候要激活它,让其显示
58 obj.SetActive(true);
59
60 return obj;
61 }
62 }
63
64
65
66
67 //缓存池模块
68 public class PoolMgr : BaseManager<PoolMgr>
69 {
70
71 //1,创建抽屉
72 public Dictionary<string, poolData> poolDic = new Dictionary<string, poolData>();
73
74 private GameObject poolObj;
75
76
77 //2,取出物品
78 public GameObject GetObj(string name)
79 {
80 GameObject obj = null;
81
82 //有抽屉,并且抽屉里的东西数量大于0 poolDic[name]==List<GameObject>
83 if (poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
84 {
85 obj = poolDic[name].GetObj();
86
87 }
88 else
89 {
90 obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
91 //把对象名字改的和池子名字一样
92 obj.name = name;
93 }
94
95 return obj;
96 }
97
98
99 //3,放入物品
100 /// <summary>
101 /// 把物体移回对象池中
102 /// </summary>
103 /// <param name="name">要移回的物品名字</param>
104 /// <param name="obj">要移回到的箱子</param>
105 public void PushObj(string name,GameObject obj)
106 {
107
108 if (poolObj == null)
109 {
110 poolObj = new GameObject("pool");
111
112 }
113
114 //里面有抽屉
115 if (poolDic.ContainsKey(name))
116 {
117 poolDic[name].PushObj(obj);
118 }
119 else //没有抽屉的时候,要创建一个抽屉
120 {
121 poolDic.Add(name,new poolData(obj,poolObj) { });
122 }
123
124 }
125
126 /// <summary>
127 /// 清空缓存池的方法
128 /// 主要用在场景切换时
129 /// </summary>
130 public void Clear()
131 {
132 //清空缓存池
133 poolDic.Clear();
134
135 poolObj = null;
136 }
137
138 }