-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject-pool.cs
More file actions
46 lines (38 loc) · 1.42 KB
/
object-pool.cs
File metadata and controls
46 lines (38 loc) · 1.42 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
// Object Pool Pattern
// Reuse objects instead of Instantiate/Destroy to reduce GC pressure.
// Uses Unity's built-in ObjectPool<T> for thread-safe pooling.
using UnityEngine;
using UnityEngine.Pool;
namespace MyGame
{
public class ProjectilePool : MonoBehaviour
{
[SerializeField] private GameObject _prefab;
[SerializeField] private int _defaultCapacity = 20;
[SerializeField] private int _maxSize = 100;
private ObjectPool<GameObject> _pool;
private void Awake()
{
_pool = new ObjectPool<GameObject>(
createFunc: CreateProjectile,
actionOnGet: OnGetProjectile,
actionOnRelease: OnReleaseProjectile,
actionOnDestroy: OnDestroyProjectile,
collectionCheck: true,
defaultCapacity: _defaultCapacity,
maxSize: _maxSize
);
}
public GameObject Get() => _pool.Get();
public void Release(GameObject obj) => _pool.Release(obj);
private GameObject CreateProjectile()
{
var obj = Instantiate(_prefab);
obj.SetActive(false);
return obj;
}
private void OnGetProjectile(GameObject obj) => obj.SetActive(true);
private void OnReleaseProjectile(GameObject obj) => obj.SetActive(false);
private void OnDestroyProjectile(GameObject obj) => Destroy(obj);
}
}