|
1 | 1 | # Object-Pooling-for-Unity
|
2 | 2 | Object Pooling for Unity
|
| 3 | + |
| 4 | +## Features |
| 5 | +- Faster in terms of performance than Instantiate/Destroy |
| 6 | +- Easy to use |
| 7 | +- Easy to integrate with already written spawn systems |
| 8 | +- Callbacks OnSpawn & OnDespawn for resseting after object being used |
| 9 | + |
| 10 | +## Usage |
| 11 | +How to populate pool: |
| 12 | +```csharp |
| 13 | +using ToolBox.Pools; |
| 14 | +using UnityEngine; |
| 15 | + |
| 16 | +public class Spawner : MonoBehaviour |
| 17 | +{ |
| 18 | + [SerializeField] private GameObject _prefab = null; |
| 19 | + |
| 20 | + private void Awake() |
| 21 | + { |
| 22 | + // Use this only with Prefabs |
| 23 | + _prefab.Populate(count: 50); |
| 24 | + } |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +Also, you can just put PoolInstaller component on any object on Scene and select which objects you want to prepopulate |
| 29 | + |
| 30 | + |
| 31 | +How to spawn object from pool: |
| 32 | +```csharp |
| 33 | +using ToolBox.Pools; |
| 34 | +using UnityEngine; |
| 35 | + |
| 36 | +public class Spawner : MonoBehaviour |
| 37 | +{ |
| 38 | + [SerializeField] private GameObject _prefab = null; |
| 39 | + |
| 40 | + public void Spawn() |
| 41 | + { |
| 42 | + // Use this only with Prefabs |
| 43 | + _prefab.Spawn(transform.position, transform.rotation); |
| 44 | + |
| 45 | + // Use this only with Prefabs |
| 46 | + _prefab.Spawn<Rigidbody>(transform.position, transform.rotation).isKinematic = true; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +``` |
| 51 | + |
| 52 | +How to return object to pool: |
| 53 | +```csharp |
| 54 | +using ToolBox.Pools; |
| 55 | +using UnityEngine; |
| 56 | + |
| 57 | +public class Spawner : MonoBehaviour |
| 58 | +{ |
| 59 | + [SerializeField] private GameObject _prefab = null; |
| 60 | + |
| 61 | + public void Spawn() |
| 62 | + { |
| 63 | + // Use this only with Prefabs |
| 64 | + var instance = _prefab.Spawn(transform.position, transform.rotation); |
| 65 | + |
| 66 | + // Use this only with Instances of Prefab |
| 67 | + instance.Despawn(); |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +How to use callbacks: |
| 73 | +```csharp |
| 74 | +using ToolBox.Pools; |
| 75 | +using UnityEngine; |
| 76 | + |
| 77 | +public class Health : MonoBehaviour, IPoolable |
| 78 | +{ |
| 79 | + [SerializeField] private float _maxHealth = 100f; |
| 80 | + |
| 81 | + private float _health = 0f; |
| 82 | + |
| 83 | + private void Awake() => |
| 84 | + _health = _maxHealth; |
| 85 | + |
| 86 | + // IPoolable method |
| 87 | + public void OnSpawn() => |
| 88 | + _health = _maxHealth; |
| 89 | + |
| 90 | + // IPoolable method |
| 91 | + public void OnDespawn() { } |
| 92 | +} |
| 93 | +``` |
0 commit comments