forked from nhathuy7996/ReUseScript_Unity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectPoolingX.cs
75 lines (61 loc) · 1.8 KB
/
ObjectPoolingX.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolingX<T> : MonoBehaviour where T: MonoBehaviour
{
private static ObjectPoolingX<T> _instant;
public static ObjectPoolingX<T> Instant => _instant;
private void Awake()
{
if (_instant == null)
_instant = this;
if (_instant.gameObject.GetInstanceID() != this.gameObject.GetInstanceID())
{
Destroy(this.gameObject);
}
}
Dictionary<T, List<T>> _poolObjects = new Dictionary<T, List<T>>();
Dictionary<GameObject, List<GameObject>> _poolObjects2 = new Dictionary<GameObject, List<GameObject>>();
public T GetObjectType(T key)
{
List<T> _itemPool = new List<T>();
if (!_poolObjects.ContainsKey(key))
{
_poolObjects.Add(key, _itemPool);
}
else
{
_itemPool = _poolObjects[key];
}
foreach (T g in _itemPool)
{
if (g.gameObject.activeSelf)
continue;
return g;
}
T g2 = Instantiate(key, this.transform.position, Quaternion.identity);
_poolObjects[key].Add(g2);
return g2;
}
public GameObject GetObject(GameObject key)
{
List<GameObject> _itemPool = new List<GameObject>();
if (!_poolObjects2.ContainsKey(key))
{
_poolObjects2.Add(key, _itemPool);
}
else
{
_itemPool = _poolObjects2[key];
}
foreach (GameObject g in _itemPool)
{
if (g.gameObject.activeSelf)
continue;
return g;
}
GameObject g2 = Instantiate(key, this.transform.position, Quaternion.identity);
_poolObjects2[key].Add(g2);
return g2;
}
}