1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4
5 public class ObjectPool : MonoBehaviour {
6 public static ObjectPool instance;
7 Dictionary<string, Stack<GameObject>> pools = new Dictionary<string, Stack<GameObject>>();
8 //Stack<GameObject> pool=new Stack<GameObject>();
9 void Start () {
10 instance = this;
11
12 }
13 public void Delete(string key,GameObject g)
14 {
15 g.SetActive(false);
16 pools[key].Push(g);
17 }
18 public GameObject Creat(string key,GameObject prefab,Vector3 position,Quaternion qua)
19 {
20 GameObject g=null;
21 if (pools.ContainsKey(key))
22 {
23 if (pools[key].Count > 0)
24 {
25 g = pools[key].Pop();
26 g.SetActive(true);
27 g.transform.position = position;
28 g.transform.rotation = qua;
29 }
30 else
31 {
32 g = Instantiate(prefab, position, qua);
33 }
34 }
35 else
36 {
37 pools.Add(key, new Stack<GameObject>());
38 g = Instantiate(prefab, position, qua);
39
40 }
41 return g;
42 }
43 void Update () {
44
45 }
46 }
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolTest : MonoBehaviour {
public GameObject[] prefab;
public Stack<GameObject> s=new Stack<GameObject>();
public int set = 0;
void Start () {
}
public void Creat()
{
s.Push(ObjectPool.instance.Creat(set.ToString(),prefab[set], Vector3.one, Quaternion.identity));
}
public void Delete()
{
ObjectPool.instance.Delete(set.ToString(),s.Pop());
}
void Update () {
}
}