-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUnityPool.cs
More file actions
66 lines (48 loc) · 1.19 KB
/
Copy pathUnityPool.cs
File metadata and controls
66 lines (48 loc) · 1.19 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
using System.Collections.Generic;
using UnityEngine;
public class UnityPool<T> : MonoBehaviour where T : MonoBehaviour
{
public T _Prefab;
public bool _DoPrewarm;
[Range(1, 1000)]
public int _PrewarmCount;
private static UnityPool<T> _Instance;
private Queue<GameObject> _Pool;
private void Awake()
{
_Instance = this;
_Pool = new Queue<GameObject>();
if (_DoPrewarm)
Add(_PrewarmCount);
Debug.Log("Pool for type " + typeof(T).Name + " Objects : " + _Pool.Count);
}
public static UnityPool<T> GetInstance()
{
return _Instance;
}
public void Return(GameObject obj)
{
obj.SetActive(false);
obj.transform.SetParent(transform);
_Pool.Enqueue(obj);
}
public GameObject Get()
{
if (_Pool.Count == 0)
{
Add();
}
var obj = _Pool.Dequeue();
obj.transform.SetParent(null);
obj.SetActive(true);
return obj;
}
private void Add(int Count = 1)
{
for (int i = 0; i < Count; i++)
{
var tmp = Instantiate(_Prefab.gameObject);
Return(tmp);
}
}
}