This repository has been archived by the owner on Aug 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ObjectPooler.cs
85 lines (76 loc) · 2.1 KB
/
ObjectPooler.cs
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
/* This class is used for pooling objects and reusing objects for performance
* This works best when lots of the same object are spawned multiple times
* such as projectiles from a gun */
public class ObjectPooler : MonoBehaviour
{
public static ObjectPooler instance;
public List<PrePooledObjects> prePooledObjects;
private Dictionary<string, Queue<GameObject>> dict = null;
[Serializable]
public struct PrePooledObjects
{
public GameObject gameObject;
public int count;
}
void Awake()
{
if (instance == null)
{
instance = this;
dict = new Dictionary<string, Queue<GameObject>>();
}
else
{
Destroy(this);
}
}
private void Start()
{
List<GameObject> pooledObjects = new List<GameObject>();
foreach(PrePooledObjects prePoolObj in prePooledObjects)
{
for(int i = 0; i<prePoolObj.count; i++)
{
pooledObjects.Add(GetPooledObject(prePoolObj.gameObject));
}
}
foreach(GameObject go in pooledObjects)
{
go.SetActive(false);
}
}
public GameObject GetPooledObject(GameObject go)
{
if (!dict.ContainsKey(go.name))
{
dict.Add(go.name, new Queue<GameObject>());
}
if (dict[go.name].Count > 0)
{
return dict[go.name].Dequeue();
}
else
{
GameObject newGo = Instantiate(go);
PoolableObject po = newGo.GetComponent<PoolableObject>();
if( po == null)
{
po = newGo.AddComponent<PoolableObject>();
}
po.prefab = go;
return newGo;
}
}
public void ReleasePooledObject(PoolableObject po)
{
if (!dict.ContainsKey(po.prefab.name))
{
dict.Add(po.prefab.name, new Queue<GameObject>());
}
dict[po.prefab.name].Enqueue(po.gameObject);
}
}