Repository navigation
Expand file tree
/
Copy pathGameObjectPool.cs
More file actions
67 lines (56 loc) · 1.75 KB
/
Copy pathGameObjectPool.cs
File metadata and controls
67 lines (56 loc) · 1.75 KB
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
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
namespace Unity.Pool
{
public class GameObjectPool : MonoBehaviour
{
public static GameObjectPool Instance;
[SerializeField]
private GameObject[] Prefabs;
public int MaxPoolSize = 64;
private Dictionary<string, IObjectPool<GameObject>> m_PoolDictionary;
public void ReleaseObject(string value, GameObject obj)
{
var pool = m_PoolDictionary[value];
pool.Release(obj);
}
public GameObject PlaceObject(string prefabName, Vector3 position)
{
var pool = m_PoolDictionary[prefabName];
var obj = pool.Get();
obj.transform.position = position;
return obj;
}
private void Awake()
{
Instance = this;
m_PoolDictionary = new Dictionary<string, IObjectPool<GameObject>>();
foreach (var prefab in Prefabs)
{
m_PoolDictionary.Add(
prefab.name,
new ObjectPool<GameObject>(
() => Instantiate(prefab),
OnTakeFromPool, OnReturnedToPool, OnDestroyPoolObject, true, 10, MaxPoolSize));
}
}
private void OnDestroy()
{
if (Instance == this)
Instance = null;
}
private void OnReturnedToPool(GameObject obj)
{
obj.gameObject.SetActive(false);
}
private void OnTakeFromPool(GameObject obj)
{
obj.gameObject.SetActive(true);
}
private void OnDestroyPoolObject(GameObject obj)
{
Destroy(obj.gameObject);
}
}
}