forked from Rfrixy/Generic-Unity-Object-Pooler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectPooler.cs
108 lines (82 loc) · 2.35 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class ObjectPoolItem
{
public GameObject objectToPool;
public int amountToPool;
public bool shouldExpand = true;
public ObjectPoolItem(GameObject obj, int amt, bool exp = true)
{
objectToPool = obj;
amountToPool = Mathf.Max(amt,2);
shouldExpand = exp;
}
}
public class ObjectPooler : MonoBehaviour
{
public static ObjectPooler SharedInstance;
public List<ObjectPoolItem> itemsToPool;
public List<List<GameObject>> pooledObjectsList;
public List<GameObject> pooledObjects;
private List<int> positions;
void Awake()
{
SharedInstance = this;
pooledObjectsList = new List<List<GameObject>>();
pooledObjects = new List<GameObject>();
positions = new List<int>();
for (int i = 0; i < itemsToPool.Count; i++)
{
ObjectPoolItemToPooledObject(i);
}
}
public GameObject GetPooledObject(int index)
{
int curSize = pooledObjectsList[index].Count;
for (int i = positions[index] + 1; i < positions[index] + pooledObjectsList[index].Count; i++)
{
if (!pooledObjectsList[index][i % curSize].activeInHierarchy)
{
positions[index] = i % curSize;
return pooledObjectsList[index][i % curSize];
}
}
if (itemsToPool[index].shouldExpand)
{
GameObject obj = (GameObject)Instantiate(itemsToPool[index].objectToPool);
obj.SetActive(false);
obj.transform.parent = this.transform;
pooledObjectsList[index].Add(obj);
return obj;
}
return null;
}
public List<GameObject> GetAllPooledObjects(int index)
{
return pooledObjectsList[index];
}
public int AddObject(GameObject GO, int amt = 3, bool exp = true)
{
ObjectPoolItem item = new ObjectPoolItem(GO, amt, exp);
int currLen = itemsToPool.Count;
itemsToPool.Add(item);
ObjectPoolItemToPooledObject(currLen);
return currLen;
}
void ObjectPoolItemToPooledObject(int index)
{
ObjectPoolItem item = itemsToPool[index];
pooledObjects = new List<GameObject>();
for (int i = 0; i < item.amountToPool; i++)
{
GameObject obj = (GameObject)Instantiate(item.objectToPool);
obj.SetActive(false);
obj.transform.parent = this.transform;
pooledObjects.Add(obj);
}
pooledObjectsList.Add(pooledObjects);
positions.Add(0);
}
}