/
TrashManRecycleBin.cs
executable file
·230 lines (181 loc) · 5.51 KB
/
TrashManRecycleBin.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
[System.Serializable]
public sealed class TrashManRecycleBin
{
/// <summary>
/// Fired when the GameObject was just spawned
/// </summary>
public event Action<GameObject> onSpawnedEvent;
/// <summary>
/// Fired when the GameObject was just despawned
/// </summary>
public event Action<GameObject> onDespawnedEvent;
/// <summary>
/// The prefab or GameObject in the scene managed by this class.
/// </summary>
public GameObject prefab;
/// <summary>
/// total number of instances to create at start
/// </summary>
public int instancesToPreallocate = 5;
/// <summary>
/// total number of instances to allocate if one is requested when the bin is empty
/// </summary>
public int instancesToAllocateIfEmpty = 1;
/// <summary>
/// if true, the recycle bin will not create any more instances when hardLimit is reached and will instead return null for any spanws
/// </summary>
public bool imposeHardLimit = false;
/// <summary>
/// if imposeHardLimit is true, this will be the maximum number of instances to create
/// </summary>
public int hardLimit = 5;
/// <summary>
/// if true, any excess instances will be culled at regular intervals
/// </summary>
public bool cullExcessPrefabs = false;
/// <summary>
/// total instances to keep in the pool. All excess will be culled if cullExcessPrefabs is true
/// </summary>
public int instancesToMaintainInPool = 5;
/// <summary>
/// how often in seconds should culling occur
/// </summary>
public float cullInterval = 10f;
/// <summary>
/// if true, the GameObject must contain a ParticleSystem! It will be automatically despawned after system.duration.
/// </summary>
public bool automaticallyRecycleParticleSystems = false;
/// <summary>
/// if true and TrashMan.persistBetweenScenes is true this recycle bin will not be purged when a new level loads
/// </summary>
public bool persistBetweenScenes = false;
/// <summary>
/// stores all of our GameObjects
/// </summary>
Stack<GameObject> _gameObjectPool;
/// <summary>
/// last time culling happened
/// </summary>
float _timeOfLastCull = float.MinValue;
/// <summary>
/// keeps track of the total number of instances spawned
/// </summary>
int _spawnedInstanceCount = 0;
#region Private
/// <summary>
/// allocates
/// </summary>
/// <param name="count">Count.</param>
void allocateGameObjects( int count )
{
if( imposeHardLimit && _gameObjectPool.Count + count > hardLimit )
count = hardLimit - _gameObjectPool.Count;
for( int n = 0; n < count; n++ )
{
GameObject go = GameObject.Instantiate( prefab.gameObject ) as GameObject;
go.name = prefab.name;
if( go.transform as RectTransform )
go.transform.SetParent( TrashMan.instance.transform, false );
else
go.transform.parent = TrashMan.instance.transform;
go.SetActive( false );
_gameObjectPool.Push( go );
}
}
/// <summary>
/// pops an object off the stack. Returns null if we hit the hardLimit.
/// </summary>
GameObject pop()
{
if( imposeHardLimit && _spawnedInstanceCount >= hardLimit )
return null;
if( _gameObjectPool.Count > 0 )
{
_spawnedInstanceCount++;
return _gameObjectPool.Pop();
}
allocateGameObjects( instancesToAllocateIfEmpty );
return pop();
}
#endregion
#region Public
/// <summary>
/// preps the Stack and does preallocation
/// </summary>
public void initialize()
{
//prefab.prefabPoolName = prefab.gameObject.name;
_gameObjectPool = new Stack<GameObject>( instancesToPreallocate );
allocateGameObjects( instancesToPreallocate );
}
/// <summary>
/// culls any excess objects if necessary
/// </summary>
public void cullExcessObjects()
{
if( !cullExcessPrefabs || _gameObjectPool.Count <= instancesToMaintainInPool )
return;
if( Time.time > _timeOfLastCull + cullInterval )
{
_timeOfLastCull = Time.time;
for( int n = instancesToMaintainInPool; n <= _gameObjectPool.Count; n++ )
GameObject.Destroy( _gameObjectPool.Pop() );
}
}
/// <summary>
/// fetches a new instance from the recycle bin. Returns null if we reached the hardLimit.
/// </summary>
public GameObject spawn()
{
var go = pop();
if( go != null )
{
if( onSpawnedEvent != null )
onSpawnedEvent( go );
if( automaticallyRecycleParticleSystems )
{
var system = go.GetComponent<ParticleSystem>();
if( system )
{
// we add the startLifetime to the system's duration to avoid it getting recycled while emitting.
// note that curves can extend the startLifetime so this isn't perfect
TrashMan.despawnAfterDelay( go, system.duration + system.startLifetime );
}
else
{
Debug.LogError( "automaticallyRecycleParticleSystems is true but there is no ParticleSystem on this GameObject!" );
}
}
}
return go;
}
/// <summary>
/// returns an instance to the recycle bin
/// </summary>
/// <param name="go">Go.</param>
public void despawn( GameObject go )
{
go.SetActive( false );
_spawnedInstanceCount--;
_gameObjectPool.Push( go );
if( onDespawnedEvent != null )
onDespawnedEvent( go );
}
/// <summary>
/// clears out the bin optionally calling Destroy on all objects in it. note than any spawned objects are not touched by this operation!
/// </summary>
public void clearBin( bool shouldDestroyAllManagedObjects )
{
while( _gameObjectPool.Count > 0 )
{
var go = _gameObjectPool.Pop();
if( shouldDestroyAllManagedObjects )
GameObject.Destroy( go );
}
}
#endregion
}