-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathObjectPool.cs
More file actions
107 lines (78 loc) · 2.68 KB
/
ObjectPool.cs
File metadata and controls
107 lines (78 loc) · 2.68 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
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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
public class ObjectPoolItem {
public GameObject parentObject;
public GameObject itemObject;
}
*/
// The ObjectPool is the storage class for pooled objects of the same kind (e.g. "Pistol Bullet", or "Enemy A")
// This is used by the ObjectPoolManager and is not meant to be used separately
public class ObjectPool : System.Object {
public int maxPoolItems = 5000;
// The type of object this pool is handling
public GameObject prefab;
// This stores the cached objects waiting to be reactivated
//public Dictionary<int, GameObject> pool;
public Queue<GameObject> pool;
public string key = "default";
// How many objects are currently sitting in the cache
public int Count {
get { return pool.Count; }
}
public ObjectPool() {
pool = new Queue<GameObject>();
}
public GameObject instantiate(Vector3 position, Quaternion rotation) {
GameObject obj;
if (pool.Count > maxPoolItems) {
//return null;
}
// if we don't have any object already in the cache, create a new one
if (pool.Count == 0 || pool.Count > maxPoolItems) {
obj = UnityEngine.Object.Instantiate(prefab, position, rotation) as GameObject;
}
else { // else pull one from the cache
obj = pool.Dequeue();
// reactivate the object
obj.transform.parent = null;
obj.transform.position = position;
obj.transform.rotation = rotation;
obj.SetActive(true);
// Call Start again
obj.SendMessage("Start", SendMessageOptions.DontRequireReceiver);
}
return obj;
}
// put the object in the cache and deactivate it
public void recycle(GameObject obj, string key = null) {
if (obj == null) {
return;
}
if (pool.Count > maxPoolItems) {
obj.DestroyGameObject(0, false);
return;
}
// deactivate the object
obj.SetActive(false);
// put the recycled object in this ObjectPool's bucket
if (!string.IsNullOrEmpty(key)) {
obj.transform.parent = ObjectPoolKeyedManager.instance.gameObject.transform;
}
else {
obj.transform.parent = ObjectPoolManager.instance.gameObject.transform;
}
if (!pool.Contains(obj)) {
// put object back in cache for reuse later
pool.Enqueue(obj);
}
}
public void clear() {
foreach (GameObject go in pool) {
go.DestroyNow();
}
pool.Clear();
}
}