-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenericObjectPool.cs
76 lines (64 loc) · 1.89 KB
/
GenericObjectPool.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class GenericObjectPool<T> : MonoBehaviour where T : Component
{
#region Fields
[SerializeField]
private T prefab;
private Queue<T> pooledObjects = new Queue<T>();
#endregion
#region Singleton
//Singleton Instantiation
public static GenericObjectPool<T> Instance { get; private set; }
private void Awake()
{
if (Instance != null && Instance != this)
Destroy(this.gameObject);
else
Instance = this;
DontDestroyOnLoad(this);
}
#endregion
#region Public Pool Accessing
/// <summary>
/// Gets Object of Type T from Pool
/// </summary>
/// <returns>Object of Type T</returns>
public T Get()
{
if (pooledObjects.Count == 0)
AddObjects(1);
return pooledObjects.Dequeue();
}
/// <summary>
/// Recycles object that was being used back into the active pool
/// </summary>
/// <param name="objectToSet"></param>
public void Recycle(T objectToSet)
{
objectToSet.gameObject.SetActive(false);
pooledObjects.Enqueue(objectToSet);
}
#endregion
#region Pool Modifying
/// <summary>
///
/// </summary>
/// <param name="count"></param>
private void AddObjects(int count)
{
for (int i = 0; i < count; i++)
{
var newObject = Instantiate(prefab, Vector3.zero, Quaternion.identity, transform);
AddPoolReference(newObject);
Recycle(newObject);
}
}
/// <summary>
/// Adds reference to the pooled object Via Interface
/// </summary>
/// <param name="objectToAddReference"></param>
public abstract void AddPoolReference(T objectToAddReference);
#endregion
}