forked from nhathuy7996/ReUseScript_Unity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LazyPooling.cs
110 lines (90 loc) · 3.04 KB
/
LazyPooling.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
109
110
using System.Collections.Generic;
using UnityEngine;
namespace HuynnLib{
public class LazyPooling : MonoBehaviour
{
private static LazyPooling _instant;
public static LazyPooling Instant {
get
{
if (_instant == null)
{
if (FindObjectOfType<LazyPooling>() != null)
_instant = FindObjectOfType<LazyPooling>();
else
new GameObject().AddComponent<LazyPooling>().name = "Singleton_"+ typeof(LazyPooling).ToString();
}
return _instant;
}
}
void Awake()
{
if (_instant != null && _instant.gameObject.GetInstanceID() != this.gameObject.GetInstanceID())
{
Debug.LogError("Singleton already exist "+ _instant.gameObject.name);
Destroy(this.gameObject);
}
else
_instant = this.GetComponent<LazyPooling>();
}
Dictionary<GameObject, List<GameObject>> _poolObjects2 = new Dictionary<GameObject, List<GameObject>>();
public GameObject GetObj(GameObject objKey, bool isKeepParent = false){
if (!_poolObjects2.ContainsKey(objKey))
{
_poolObjects2.Add(objKey, new List<GameObject>());
}
foreach (var g in _poolObjects2[objKey])
{
if (g.gameObject.activeSelf)
continue;
return g;
}
GameObject g2 = Instantiate(objKey);
_poolObjects2[objKey].Add(g2);
if (isKeepParent)
g2.transform.SetParent(objKey.transform.parent);
return g2;
}
Dictionary<Component, List<Component>> _poolObjt = new Dictionary<Component, List<Component>>();
public T getObj<T>(T objKey, bool isKeepParent = false) where T : Component
{
if (!_poolObjt.ContainsKey(objKey))
{
_poolObjt.Add(objKey, new List<Component>());
}
foreach (T g in _poolObjt[objKey])
{
if (g.gameObject.activeSelf)
continue;
return g;
}
T g2 = Instantiate(objKey);
_poolObjt[objKey].Add(g2);
if (isKeepParent)
g2.transform.SetParent(objKey.transform.parent);
return g2;
}
public void resetObj<T>( T objKey) where T:Component
{
if (!_poolObjt.ContainsKey(objKey))
{
return;
}
foreach (T g in _poolObjt[objKey])
{
g.gameObject.SetActive(false);
}
}
public void CreatePool<T>(T keyObj, int size) where T : Component
{
if (!_poolObjt.ContainsKey(keyObj))
{
_poolObjt.Add(keyObj, new List<Component>());
}
for (int i = 0; i < size; i++)
{
this.getObj<T>(keyObj,true).gameObject.SetActive(false);
}
}
}
}