wangguan
2020-12-12 938aa4da26e0109e16ded70d13a43c187498b901
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
 
namespace Core.Utilities
{
    /// <summary>
    /// Maintains a pool of objects
    /// </summary>
    public class Pool<T>
    {
        /// <summary>
        /// Our factory function
        /// </summary>
        protected Func<T> m_Factory;
 
        /// <summary>
        /// Our resetting function
        /// </summary>
        protected readonly Action<T> m_Reset;
 
        /// <summary>
        /// A list of all m_Available items
        /// </summary>
        protected readonly List<T> m_Available;
 
        /// <summary>
        /// A list of all items managed by the pool
        /// </summary>
        protected readonly List<T> m_All;
 
        /// <summary>
        /// Create a new pool with a given number of starting elements
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        /// <param name="reset">Function to use to m_Reset items when retrieving from the pool</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public Pool(Func<T> factory, Action<T> reset, int initialCapacity)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
 
            m_Available = new List<T>();
            m_All = new List<T>();
            m_Factory = factory;
            m_Reset = reset;
 
            if (initialCapacity > 0)
            {
                Grow(initialCapacity);
            }
        }
 
        /// <summary>
        /// Creates a new blank pool
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        public Pool(Func<T> factory)
            : this(factory, null, 0)
        {
        }
 
        /// <summary>
        /// Create a new pool with a given number of starting elements
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public Pool(Func<T> factory, int initialCapacity)
            : this(factory, null, initialCapacity)
        {
        }
 
        /// <summary>
        /// Gets an item from the pool, growing it if necessary
        /// </summary>
        /// <returns></returns>
        public virtual T Get()
        {
            return Get(m_Reset);
        }
 
        /// <summary>
        /// Gets an item from the pool, growing it if necessary, and with a specified m_Reset function
        /// </summary>
        /// <param name="resetOverride">A function to use to m_Reset the given object</param>
        public virtual T Get(Action<T> resetOverride)
        {
            if (m_Available.Count == 0)
            {
                Grow(1);
            }
            if (m_Available.Count == 0)
            {
                throw new InvalidOperationException("Failed to grow pool");
            }
 
            int itemIndex = m_Available.Count - 1;
            T item = m_Available[itemIndex];
            m_Available.RemoveAt(itemIndex);
 
            if (resetOverride != null)
            {
                resetOverride(item);
            }
 
            return item;
        }
 
        /// <summary>
        /// Gets whether or not this pool contains a specified item
        /// </summary>
        public virtual bool Contains(T pooledItem)
        {
            return m_All.Contains(pooledItem);
        }
 
        /// <summary>
        /// Return an item to the pool
        /// </summary>
        public virtual void Return(T pooledItem)
        {
            if (m_All.Contains(pooledItem) &&
                !m_Available.Contains(pooledItem))
            {
                ReturnToPoolInternal(pooledItem);
            }
            else
            {
                throw new InvalidOperationException("Trying to return an item to a pool that does not contain it: " + pooledItem +
                                                    ", " + this);
            }
        }
 
        /// <summary>
        /// Return all items to the pool
        /// </summary>
        public virtual void ReturnAll()
        {
            ReturnAll(null);
        }
 
        /// <summary>
        /// Returns all items to the pool, and calls a delegate on each one
        /// </summary>
        public virtual void ReturnAll(Action<T> preReturn)
        {
            for (int i = 0; i < m_All.Count; ++i)
            {
                T item = m_All[i];
                if (!m_Available.Contains(item))
                {
                    if (preReturn != null)
                    {
                        preReturn(item);
                    }
                    ReturnToPoolInternal(item);
                }
            }
        }
 
        /// <summary>
        /// Grow the pool by a given number of elements
        /// </summary>
        public void Grow(int amount)
        {
            for (int i = 0; i < amount; ++i)
            {
                AddNewElement();
            }
        }
 
        /// <summary>
        /// Returns an object to the m_Available list. Does not check for consistency
        /// </summary>
        protected virtual void ReturnToPoolInternal(T element)
        {
            m_Available.Add(element);
        }
 
        /// <summary>
        /// Adds a new element to the pool
        /// </summary>
        protected virtual T AddNewElement()
        {
            T newElement = m_Factory();
            m_All.Add(newElement);
            m_Available.Add(newElement);
 
            return newElement;
        }
 
        /// <summary>
        /// Dummy factory that returns the default T value
        /// </summary>        
        protected static T DummyFactory()
        {
            return default(T);
        }
    }
 
    /// <summary>
    /// A variant pool that takes Unity components. Automatically enables and disables them as necessary
    /// </summary>
    public class UnityComponentPool<T> : Pool<T>
        where T : Component
    {
        /// <summary>
        /// Create a new pool with a given number of starting elements
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        /// <param name="reset">Function to use to reset items when retrieving from the pool</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public UnityComponentPool(Func<T> factory, Action<T> reset, int initialCapacity)
            : base(factory, reset, initialCapacity)
        {
        }
 
        /// <summary>
        /// Creates a new blank pool
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        public UnityComponentPool(Func<T> factory)
            : base(factory)
        {
        }
 
        /// <summary>
        /// Create a new pool with a given number of starting elements
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public UnityComponentPool(Func<T> factory, int initialCapacity)
            : base(factory, initialCapacity)
        {
        }
 
        /// <summary>
        /// Retrieve an enabled element from the pool
        /// </summary>
        public override T Get(Action<T> resetOverride)
        {
            T element = base.Get(resetOverride);
 
            element.gameObject.SetActive(true);
 
            return element;
        }
 
        /// <summary>
        /// Automatically disable returned object
        /// </summary>
        protected override void ReturnToPoolInternal(T element)
        {
            element.gameObject.SetActive(false);
 
            base.ReturnToPoolInternal(element);
        }
 
        /// <summary>
        /// Keep newly created objects disabled
        /// </summary>
        protected override T AddNewElement()
        {
            T newElement = base.AddNewElement();
 
            newElement.gameObject.SetActive(false);
 
            return newElement;
        }
    }
 
    /// <summary>
    /// A variant pool that takes Unity game objects. Automatically enables and disables them as necessary
    /// </summary>
    public class GameObjectPool : Pool<GameObject>
    {
        /// <summary>
        /// Create a new pool with a given number of starting elements
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        /// <param name="reset">Function to use to reset items when retrieving from the pool</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public GameObjectPool(Func<GameObject> factory, Action<GameObject> reset, int initialCapacity)
            : base(factory, reset, initialCapacity)
        {
        }
 
        /// <summary>
        /// Creates a new blank pool
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        public GameObjectPool(Func<GameObject> factory)
            : base(factory)
        {
        }
 
        /// <summary>
        /// Create a new pool with a given number of starting elements
        /// </summary>
        /// <param name="factory">The function that creates pool objects</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public GameObjectPool(Func<GameObject> factory, int initialCapacity)
            : base(factory, initialCapacity)
        {
        }
 
        /// <summary>
        /// Retrieve an enabled element from the pool
        /// </summary>
        public override GameObject Get(Action<GameObject> resetOverride)
        {
            GameObject element = base.Get(resetOverride);
 
            element.SetActive(true);
 
            return element;
        }
 
        /// <summary>
        /// Automatically disable returned object
        /// </summary>
        protected override void ReturnToPoolInternal(GameObject element)
        {
            element.SetActive(false);
 
            base.ReturnToPoolInternal(element);
        }
 
        /// <summary>
        /// Keep newly created objects disabled
        /// </summary>
        protected override GameObject AddNewElement()
        {
            GameObject newElement = base.AddNewElement();
 
            newElement.SetActive(false);
 
            return newElement;
        }
    }
 
    /// <summary>
    /// Variant pool that automatically instantiates objects from a given Unity gameobject prefab
    /// </summary>
    public class AutoGameObjectPrefabPool : GameObjectPool
    {
        /// <summary>
        /// Create our new prefab item clone
        /// </summary>
        GameObject PrefabFactory()
        {
            GameObject newElement = Object.Instantiate(m_Prefab);
            if (m_Initialize != null)
            {
                m_Initialize(newElement);
            }
 
            return newElement;
        }
 
        /// <summary>
        /// Our base prefab
        /// </summary>
        protected readonly GameObject m_Prefab;
 
        /// <summary>
        /// Initialisation method for objects
        /// </summary>
        protected readonly Action<GameObject> m_Initialize;
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        public AutoGameObjectPrefabPool(GameObject prefab)
            : this(prefab, null, null, 0)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialize">An initialisation function to call after creating prefabs</param>
        public AutoGameObjectPrefabPool(GameObject prefab, Action<GameObject> initialize)
            : this(prefab, initialize, null, 0)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialize">An initialisation function to call after creating prefabs</param>
        /// <param name="reset">Function to use to reset items when retrieving from the pool</param>
        public AutoGameObjectPrefabPool(GameObject prefab, Action<GameObject> initialize, Action<GameObject> reset)
            : this(prefab, initialize, reset, 0)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab with a given number of starting elements
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public AutoGameObjectPrefabPool(GameObject prefab, int initialCapacity)
            : this(prefab, null, null, initialCapacity)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialize">An initialisation function to call after creating prefabs</param>
        /// <param name="reset">Function to use to reset items when retrieving from the pool</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public AutoGameObjectPrefabPool(GameObject prefab, Action<GameObject> initialize, Action<GameObject> reset,
                                        int initialCapacity)
            : base(DummyFactory, reset, 0)
        {
            // Pass 0 to initial capacity because we need to set ourselves up first
            // We then call Grow again ourselves
            m_Initialize = initialize;
            m_Prefab = prefab;
            m_Factory = PrefabFactory;
            if (initialCapacity > 0)
            {
                Grow(initialCapacity);
            }
        }
    }
 
    /// <summary>
    /// Variant pool that automatically instantiates objects from a given Unity component prefab
    /// </summary>
    public class AutoComponentPrefabPool<T> : UnityComponentPool<T>
        where T : Component
    {
        /// <summary>
        /// Create our new prefab item clone
        /// </summary>
        T PrefabFactory()
        {
            T newElement = Object.Instantiate(m_Prefab);
            if (m_Initialize != null)
            {
                m_Initialize(newElement);
            }
 
            return newElement;
        }
 
        /// <summary>
        /// Our base prefab
        /// </summary>
        protected readonly T m_Prefab;
 
        /// <summary>
        /// Initialisation method for objects
        /// </summary>
        protected readonly Action<T> m_Initialize;
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        public AutoComponentPrefabPool(T prefab)
            : this(prefab, null, null, 0)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialize">An initialisation function to call after creating prefabs</param>
        public AutoComponentPrefabPool(T prefab, Action<T> initialize)
            : this(prefab, initialize, null, 0)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialize">An initialisation function to call after creating prefabs</param>
        /// <param name="reset">Function to use to reset items when retrieving from the pool</param>
        public AutoComponentPrefabPool(T prefab, Action<T> initialize, Action<T> reset)
            : this(prefab, initialize, reset, 0)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab with a given number of starting elements
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public AutoComponentPrefabPool(T prefab, int initialCapacity)
            : this(prefab, null, null, initialCapacity)
        {
        }
 
        /// <summary>
        /// Create a new pool for the given Unity prefab
        /// </summary>
        /// <param name="prefab">The prefab we're cloning</param>
        /// <param name="initialize">An initialisation function to call after creating prefabs</param>
        /// <param name="reset">Function to use to reset items when retrieving from the pool</param>
        /// <param name="initialCapacity">The number of elements to seed the pool with</param>
        public AutoComponentPrefabPool(T prefab, Action<T> initialize, Action<T> reset, int initialCapacity)
            : base(DummyFactory, reset, 0)
        {
            // Pass 0 to initial capacity because we need to set ourselves up first
            // We then call Grow again ourselves
            m_Initialize = initialize;
            m_Prefab = prefab;
            m_Factory = PrefabFactory;
            if (initialCapacity > 0)
            {
                Grow(initialCapacity);
            }
        }
    }
}