-
Notifications
You must be signed in to change notification settings - Fork 1
/
SimpleObjectPool.cs
69 lines (54 loc) · 1.97 KB
/
SimpleObjectPool.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
using UnityEngine;
using System.Collections.Generic;
// A very simple object pooling class
public class SimpleObjectPool : MonoBehaviour
{
// the prefab that this object pool returns instances of
public GameObject prefab;
// collection of currently inactive instances of the prefab
private Stack<GameObject> inactiveInstances = new Stack<GameObject>();
// Returns an instance of the prefab
public GameObject GetObject()
{
GameObject spawnedGameObject;
// if there is an inactive instance of the prefab ready to return, return that
if (inactiveInstances.Count > 0)
{
// remove the instance from teh collection of inactive instances
spawnedGameObject = inactiveInstances.Pop();
}
// otherwise, create a new instance
else
{
spawnedGameObject = (GameObject)GameObject.Instantiate(prefab);
// add the PooledObject component to the prefab so we know it came from this pool
PooledObject pooledObject = spawnedGameObject.AddComponent<PooledObject>();
pooledObject.pool = this;
}
// enable the instance
spawnedGameObject.transform.SetParent(null);
spawnedGameObject.SetActive(true);
// return a reference to the instance
return spawnedGameObject;
}
public void ReturnObject(GameObject toReturn)
{
PooledObject pooledObject = toReturn.GetComponent<PooledObject>();
if (pooledObject != null && pooledObject.pool == this)
{
toReturn.transform.SetParent(transform);
toReturn.SetActive(false);
inactiveInstances.Push(toReturn);
}
else
{
Debug.LogWarning(toReturn.name + "was returned to a pool it wasn't spawned from! Destroying.");
Destroy(toReturn);
}
}
}
public class PooledObject : MonoBehaviour
{
public SimpleObjectPool Pool;
internal SimpleObjectPool pool;
}