ObjectPooler.cs
1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour {
[System.Serializable]
public class Pool
{
public string tag;
public GameObject prefab;
public int size;
}
#region Singleton
public static ObjectPooler Instance;
public void Awake()
{
Instance = this;
}
#endregion
public List<Pool> pools;
public Dictionary<string, Queue<GameObject>> poolDictionary;
// Use this for initialization
void Start () {
poolDictionary = new Dictionary<string, Queue<GameObject>>();
foreach (Pool pool in pools)
{
Queue<GameObject> ObjectPool = new Queue<GameObject>();
for(int i=0;i<pool.size;i++)
{
GameObject obj = Instantiate(pool.prefab);
obj.SetActive(false);
ObjectPool.Enqueue(obj);
}
poolDictionary.Add(pool.tag, ObjectPool);
}
}
// Update is called once per frame
void Update () {
}
public void SpawnFromPool(string tag, Vector3 position)
{
if(!poolDictionary.ContainsKey(tag))
{
Debug.LogWarning("Pool with tag " + tag + " Doesn't exist");
return;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();//Dictionary에서 빼서 ObjectToSpawn에 넣는다
objectToSpawn.SetActive(true);//빼낸 데이터 활성화
objectToSpawn.transform.position = position;//위치 설정
//objectToSpawn.transform.rotation = rotation;//로테이션 설정
poolDictionary[tag].Enqueue(objectToSpawn);//빼낸거 다시 넣는다.
}
}