-
Notifications
You must be signed in to change notification settings - Fork 14
/
Pool.cs
74 lines (63 loc) · 1.51 KB
/
Pool.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
using UnityEngine;
using UnityEngine.Pool;
public class Pool : MonoBehaviour
{
public static Pool Instance;
private ObjectPool<GameObject> _ObjectPool;
private GameObject _Sphere;
GameObject CreateFunc()
{
GameObject instance = Instantiate(_Sphere);
return instance;
}
void ActionOnGet(GameObject instance)
{
instance.SetActive(true);
}
void ActionOnRelease(GameObject instance)
{
instance.SetActive(false);
}
void ActionOnDestroy(GameObject instance)
{
Destroy(instance);
}
void TakeSphereFromPool()
{
GameObject instance = _ObjectPool.Get();
instance.transform.position = new Vector3(Random.Range(-5f, 5f), 5f, Random.Range(-5f, 5f));
instance.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
public void ReturnSphereToPool(GameObject instance)
{
_ObjectPool.Release(instance);
}
void Start()
{
Instance = this;
_Sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
_Sphere.AddComponent<Rigidbody>();
_Sphere.AddComponent<SphereController>();
_ObjectPool = new ObjectPool<GameObject>(CreateFunc, ActionOnGet, ActionOnRelease, ActionOnDestroy, false, 20, 20);
InvokeRepeating("TakeSphereFromPool", 0f, 0.2f);
}
void OnDestroy()
{
_ObjectPool.Dispose();
Instance = null;
}
}
public class SphereController : MonoBehaviour
{
void Start()
{
this.name = "Instance";
}
void Update()
{
if (transform.position.y < -20.0f)
{
Pool.Instance.ReturnSphereToPool(this.gameObject);
}
}
}