11# Object Pooling for Unity
22
33### TODO
4- - [x] Zenject support
5- - [ ] Rename some API to make it more clarifying
4+ - [x] Rename API to make it more clarifying
65
76## Features
87- Faster in terms of performance than Instantiate/Destroy (Test at the end of README)
98- Easy to use
109- Easy to integrate with already written spawn systems
11- - Callbacks OnGet & OnRelease for resseting object state
12- - Works with Zenject (auto injection into pool's game objects)
10+ - Callbacks OnReuse & OnRelease to reset object's state
1311
1412## How to Install
1513### Git Installation (Best way to get latest version)
@@ -57,10 +55,10 @@ public class Spawner : MonoBehaviour
5755
5856 public void Spawn ()
5957 {
60- _prefab .Get (transform .position , transform .rotation );
58+ _prefab .Reuse (transform .position , transform .rotation );
6159
6260 // Get object from pool with component
63- _prefab .Get <Rigidbody >(transform .position , transform .rotation ).isKinematic = true ;
61+ _prefab .Reuse <Rigidbody >(transform .position , transform .rotation ).isKinematic = true ;
6462 }
6563}
6664```
@@ -76,7 +74,7 @@ public class Spawner : MonoBehaviour
7674
7775 public void Spawn ()
7876 {
79- var instance = _prefab .Get (transform .position , transform .rotation );
77+ var instance = _prefab .Reuse (transform .position , transform .rotation );
8078 instance .Release ();
8179 }
8280}
@@ -94,29 +92,26 @@ public class Health : MonoBehaviour, IPoolable
9492 private float _health = 0 f ;
9593
9694 // Awake will be called on first _prefab.Get()
97- private void Awake () =>
98- OnGet ();
95+ private void Awake ()
96+ {
97+ OnReuse ();
98+ }
9999
100100 // IPoolable method
101- // This method will be called on all next _prefab.Get()
102- public void OnGet () =>
101+ // / <summary>
102+ // / This method will be called on 2nd Reuse call.
103+ // / Use Unity's Awake method for first initialization and this method for others
104+ // / </summary>
105+ public void OnReuse ()
106+ {
103107 _health = _maxHealth ;
108+ }
104109
105110 // IPoolable method
106111 public void OnRelease () { }
107112}
108113```
109114
110- ### How to enable Zenject support
111-
112- 1 . Import [ Zenject] ( https://github.com/modesttree/Zenject ) into your project
113- 2 . Open ` Project Settings ` of your project and select ` Player ` tab
114- 3 . Find ` Scripting Define Symbols ` and add ` ZENJECT `
115- 4 . Press the ` Apply ` button
116-
117-
118- ![ ] ( https://i.imgur.com/msJUR5k.png )
119-
120115### Peformance test:
121116Creating and destroying 1000 objects.
122117
@@ -175,7 +170,7 @@ public class Tester : MonoBehaviour
175170
176171 for (int i = 0 ; i < 1000 ; i ++ )
177172 {
178- var instance = _object .Get ();
173+ var instance = _object .Reuse ();
179174 instance .Release ();
180175 }
181176
0 commit comments