/
TrashMan.cs
executable file
·335 lines (267 loc) · 9.11 KB
/
TrashMan.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class TrashMan : MonoBehaviour
{
/// <summary>
/// access to the singleton
/// </summary>
public static TrashMan instance;
/// <summary>
/// stores the recycle bins and is used to populate the lookup Dictionaries at startup
/// </summary>
[HideInInspector]
public List<TrashManRecycleBin> recycleBinCollection;
/// <summary>
/// this is how often in seconds TrashMan should cull excess objects. Setting this to 0 or a negative number will
/// fully turn off automatic culling. You can then use the TrashManRecycleBin.cullExcessObjects method manually if
/// you would still like to do any culling.
/// </summary>
public float cullExcessObjectsInterval = 10f;
/// <summary>
/// if true, DontDestroyOnLoad will be called on the TrashMan
/// </summary>
public bool persistBetweenScenes = false;
/// <summary>
/// uses the GameObject instanceId as its key for fast look-ups
/// </summary>
Dictionary<int,TrashManRecycleBin> _instanceIdToRecycleBin = new Dictionary<int,TrashManRecycleBin>();
/// <summary>
/// uses the pool name to find the GameObject instanceId
/// </summary>
Dictionary<string,int> _poolNameToInstanceId = new Dictionary<string,int>();
[HideInInspector]
public new Transform transform;
#region MonoBehaviour
void Awake()
{
if( instance != null )
{
Destroy( gameObject );
}
else
{
transform = gameObject.transform;
instance = this;
initializePrefabPools();
if( persistBetweenScenes )
DontDestroyOnLoad( gameObject );
}
// only cull if we have an interval greater than 0
if( cullExcessObjectsInterval > 0 )
StartCoroutine( cullExcessObjects() );
SceneManager.activeSceneChanged += activeSceneChanged;
}
void activeSceneChanged( Scene oldScene, Scene newScene )
{
if( oldScene.name == null )
return;
for( var i = recycleBinCollection.Count - 1; i >= 0; i-- )
{
if( !recycleBinCollection[i].persistBetweenScenes )
removeRecycleBin( recycleBinCollection[i] );
}
}
void OnApplicationQuit()
{
instance = null;
}
#endregion
#region Private
/// <summary>
/// coroutine that runs every couple seconds and removes any objects created over the recycle bins limit
/// </summary>
/// <returns>The excess objects.</returns>
IEnumerator cullExcessObjects()
{
var waiter = new WaitForSeconds( cullExcessObjectsInterval );
while( true )
{
for( var i = 0; i < recycleBinCollection.Count; i++ )
recycleBinCollection[i].cullExcessObjects();
yield return waiter;
}
}
/// <summary>
/// populats the lookup dictionaries
/// </summary>
void initializePrefabPools()
{
if( recycleBinCollection == null )
return;
foreach( var recycleBin in recycleBinCollection )
{
if( recycleBin == null || recycleBin.prefab == null )
continue;
recycleBin.initialize();
_instanceIdToRecycleBin.Add( recycleBin.prefab.GetInstanceID(), recycleBin );
_poolNameToInstanceId.Add( recycleBin.prefab.name, recycleBin.prefab.GetInstanceID() );
}
}
/// <summary>
/// internal method that actually does the work of grabbing the item from the bin and returning it
/// </summary>
/// <param name="gameObjectInstanceId">Game object instance identifier.</param>
static GameObject spawn( int gameObjectInstanceId, Vector3 position, Quaternion rotation )
{
if( instance._instanceIdToRecycleBin.ContainsKey( gameObjectInstanceId ) )
{
var newGo = instance._instanceIdToRecycleBin[gameObjectInstanceId].spawn();
if( newGo != null )
{
var newTransform = newGo.transform;
if( newTransform as RectTransform )
newTransform.SetParent( null, false );
else
newTransform.parent = null;
newTransform.position = position;
newTransform.rotation = rotation;
newGo.SetActive( true );
}
return newGo;
}
return null;
}
/// <summary>
/// internal coroutine for despawning after a delay
/// </summary>
/// <returns>The despawn after delay.</returns>
/// <param name="go">Go.</param>
/// <param name="delayInSeconds">Delay in seconds.</param>
IEnumerator internalDespawnAfterDelay( GameObject go, float delayInSeconds )
{
yield return new WaitForSeconds( delayInSeconds );
despawn( go );
}
#endregion
#region Public
/// <summary>
/// tells TrashMan to start managing the recycle bin at runtime
/// </summary>
/// <param name="recycleBin">Recycle bin.</param>
public static void manageRecycleBin( TrashManRecycleBin recycleBin )
{
// make sure we can safely add the bin!
if( instance._poolNameToInstanceId.ContainsKey( recycleBin.prefab.name ) )
{
Debug.LogError( "Cannot manage the recycle bin because there is already a GameObject with the name (" + recycleBin.prefab.name + ") being managed" );
return;
}
instance.recycleBinCollection.Add( recycleBin );
recycleBin.initialize();
instance._instanceIdToRecycleBin.Add( recycleBin.prefab.GetInstanceID(), recycleBin );
instance._poolNameToInstanceId.Add( recycleBin.prefab.name, recycleBin.prefab.GetInstanceID() );
}
/// <summary>
/// stops managing the recycle bin optionally destroying all managed objects
/// </summary>
/// <param name="recycleBin">Recycle bin.</param>
/// <param name="shouldDestroyAllManagedObjects">If set to <c>true</c> should destroy all managed objects.</param>
public static void removeRecycleBin( TrashManRecycleBin recycleBin, bool shouldDestroyAllManagedObjects = true )
{
var recycleBinName = recycleBin.prefab.name;
// make sure we are managing the bin first
if( instance._poolNameToInstanceId.ContainsKey( recycleBinName ) )
{
instance._poolNameToInstanceId.Remove( recycleBinName );
instance._instanceIdToRecycleBin.Remove( recycleBin.prefab.GetInstanceID() );
instance.recycleBinCollection.Remove( recycleBin );
recycleBin.clearBin( shouldDestroyAllManagedObjects );
}
}
/// <summary>
/// pulls an object out of the recycle bin
/// </summary>
/// <param name="go">Go.</param>
public static GameObject spawn( GameObject go, Vector3 position = default( Vector3 ), Quaternion rotation = default( Quaternion ) )
{
if( instance._instanceIdToRecycleBin.ContainsKey( go.GetInstanceID() ) )
{
return spawn( go.GetInstanceID(), position, rotation );
}
else
{
Debug.LogWarning( "attempted to spawn go (" + go.name + ") but there is no recycle bin setup for it. Falling back to Instantiate" );
var newGo = GameObject.Instantiate( go, position, rotation ) as GameObject;
if( newGo.transform as RectTransform != null )
newGo.transform.SetParent( null, false );
else
newGo.transform.parent = null;
return newGo;
}
}
/// <summary>
/// pulls an object out of the recycle bin using the bin's name
/// </summary>
public static GameObject spawn( string gameObjectName, Vector3 position = default( Vector3 ), Quaternion rotation = default( Quaternion ) )
{
int instanceId = -1;
if( instance._poolNameToInstanceId.TryGetValue( gameObjectName, out instanceId ) )
{
return spawn( instanceId, position, rotation );
}
else
{
Debug.LogError( "attempted to spawn a GameObject from recycle bin (" + gameObjectName + ") but there is no recycle bin setup for it" );
return null;
}
}
/// <summary>
/// sticks the GameObject back into its recycle bin. If the GameObject has no bin it is destroyed.
/// </summary>
/// <param name="go">Go.</param>
public static void despawn( GameObject go )
{
if( go == null )
return;
var goName = go.name;
if( !instance._poolNameToInstanceId.ContainsKey( goName ) )
{
Destroy( go );
}
else
{
instance._instanceIdToRecycleBin[instance._poolNameToInstanceId[goName]].despawn( go );
if( go.transform as RectTransform != null )
go.transform.SetParent( instance.transform, false );
else
go.transform.parent = instance.transform;
}
}
/// <summary>
/// sticks the GameObject back into it's recycle bin after a delay. If the GameObject has no bin it is destroyed.
/// </summary>
/// <param name="go">Go.</param>
public static void despawnAfterDelay( GameObject go, float delayInSeconds )
{
if( go == null )
return;
instance.StartCoroutine( instance.internalDespawnAfterDelay( go, delayInSeconds ) );
}
/// <summary>
/// gets the recycle bin for the given GameObject name. Returns null if none exists.
/// </summary>
public static TrashManRecycleBin recycleBinForGameObjectName( string gameObjectName )
{
if( instance._poolNameToInstanceId.ContainsKey( gameObjectName ) )
{
var instanceId = instance._poolNameToInstanceId[gameObjectName];
return instance._instanceIdToRecycleBin[instanceId];
}
return null;
}
/// <summary>
/// gets the recycle bin for the given GameObject. Returns null if none exists.
/// </summary>
/// <returns>The bin for game object.</returns>
/// <param name="go">Go.</param>
public static TrashManRecycleBin recycleBinForGameObject( GameObject go )
{
TrashManRecycleBin recycleBin;
if( instance._instanceIdToRecycleBin.TryGetValue( go.GetInstanceID(), out recycleBin ) )
return recycleBin;
return null;
}
#endregion
}