-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectPoolManager.cs
66 lines (56 loc) · 1.57 KB
/
ObjectPoolManager.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolManager : MonoBehaviour
{
public static ObjectPoolManager Instance;
[Header("Pool Settings")]
public GameObject objPrefab;
public int poolSize = 10;
private Queue<GameObject> pool;
private void Awake()
{
InitializePool();
}
private void InitializePool()
{
pool = new Queue<GameObject>();
for (int i = 0; i < poolSize; i++)
{
GameObject obj = Instantiate(objPrefab, transform);
obj.SetActive(false);
pool.Enqueue(obj);
}
}
public GameObject GetObject()
{
if (pool.Count > 0)
{
GameObject obj = pool.Dequeue();
obj.SetActive(true);
return obj;
}
else
{
// If pool is empty, instantiate a new object
GameObject obj = Instantiate(objPrefab, transform);
return obj;
}
}
public void ReleaseObject(GameObject obj)
{
obj.SetActive(false);
obj.transform.SetParent(transform);
obj.transform.localScale = Vector3.one;
pool.Enqueue(obj);
}
public void ReleaseObjectWithDelay(GameObject obj, float delay)
{
StartCoroutine(ReleaseObjectWithDelay_Co(obj, delay));
}
IEnumerator ReleaseObjectWithDelay_Co(GameObject obj, float delay)
{
yield return new WaitForSeconds(delay);
ReleaseObject(obj);
}
}