-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericPool.cs
61 lines (53 loc) · 1.53 KB
/
GenericPool.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
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Subtegral.PoolUtility
{
public class GenericPool<T> where T : PoolableObject
{
private Queue<T> pool;
private readonly int _size;
private readonly T _bluePrint;
private static Transform _runtimeObjectHolder;
public GenericPool(T obj, int size = 5)
{
pool = new Queue<T>();
this._size = Mathf.Max(size, 2);
_bluePrint = obj;
InstantiateRuntimePoolContainer();
PopulatePool();
}
private void InstantiateRuntimePoolContainer()
{
if (_runtimeObjectHolder == null)
_runtimeObjectHolder = new GameObject("Pool").transform;
}
private void PopulatePool()
{
for (var i = 0; i < _size; i++)
{
var instance = Object.Instantiate(_bluePrint, _runtimeObjectHolder, true);
instance.OnWarmUp();
pool.Enqueue(instance);
}
}
public T GetPoolType()
{
return _bluePrint;
}
public T Spawn(SpawnDataContainer container)
{
if (pool.Count < 2)
PopulatePool();
var dequeued = pool.Dequeue();
dequeued.OnSpawn(container);
return dequeued;
}
public void Despawn(T obj)
{
pool.Enqueue(obj);
obj.OnDespawn();
}
}
}