-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathObjectPoolScript.cs
54 lines (44 loc) · 1.44 KB
/
ObjectPoolScript.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolScript : MonoBehaviour
{
public GameObject prefab;
private Stack<GameObject> inactiveInstances = new Stack<GameObject>();
public GameObject GetObject()
{
GameObject spawnedGameObject;
if (inactiveInstances.Count > 0)
{
spawnedGameObject = inactiveInstances.Pop();
}
else
{
spawnedGameObject = (GameObject)GameObject.Instantiate(prefab);
PooledObject pooledObject = spawnedGameObject.AddComponent<PooledObject>();
pooledObject.pool = this;
}
spawnedGameObject.transform.SetParent(null);
spawnedGameObject.SetActive(true);
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 ObjectPoolScript pool;
}