HKI Core
ObjectPool.cs
Go to the documentation of this file.
1 using UnityEngine;
2 using System.Collections.Generic;
3 
4 namespace HKI.Core.Pooling
5 {
13  [AddComponentMenu("HKI/Misc/Object Pool")]
14  public class ObjectPool : MonoBehaviour
15  {
16  // Public variables
20  [SerializeField] GameObject Prefab = null;
21 
25  [SerializeField] bool Prewarm = true;
26 
30  [SerializeField] int InstanctiatedAmountOnPrewarm = 1;
31 
32  // Private variables
33  Queue<GameObject> objectQueue = new Queue<GameObject>();
34  List<GameObject> pooledObjects = new List<GameObject>();
35 
36  // Wake function
37  void Awake()
38  {
39  if(Prewarm)
40  {
41  for(int i = 0; i < InstanctiatedAmountOnPrewarm; i++)
42  InstanctiateObject();
43  }
44  }
45 
46  // Interface function
51  public GameObject GetNewPooledObject()
52  {
53  if(objectQueue.Count == 0)
54  InstanctiateObject();
55 
56  return objectQueue.Dequeue();
57  }
58 
63  public void GiveBack(GameObject obj)
64  {
65  if(obj != null)
66  objectQueue.Enqueue(obj);
67  }
68 
73  public void GiveBackActiveObject(GameObject obj)
74  {
75  if (obj != null)
76  {
77  obj.SetActive(false);
78  objectQueue.Enqueue(obj);
79  }
80  }
81 
82  // Helper functions
84  {
85  GameObject obj = Instantiate<GameObject>(Prefab);
86  obj.SetActive(false);
87 
88  pooledObjects.Add(obj);
89  objectQueue.Enqueue(obj);
90  }
91  }
92 }
GameObject GetNewPooledObject()
This function will return an unused object.
Definition: ObjectPool.cs:51
void GiveBack(GameObject obj)
This function will recieve an object that isn&#39;t used anymore and will handle it. This function will n...
Definition: ObjectPool.cs:63
void GiveBackActiveObject(GameObject obj)
It&#39;s similar to the GiveBack function but this function will ensure that the GameObject is disabled...
Definition: ObjectPool.cs:73
This MonoBehaviour is a pool controls a pool of objects (GameObjects).
Definition: ObjectPool.cs:14