1
1
# Object Pooling for Unity
2
2
3
3
### TODO
4
- - [x] Zenject support
5
- - [ ] Rename some API to make it more clarifying
4
+ - [x] Rename API to make it more clarifying
6
5
7
6
## Features
8
7
- Faster in terms of performance than Instantiate/Destroy (Test at the end of README)
9
8
- Easy to use
10
9
- 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
13
11
14
12
## How to Install
15
13
### Git Installation (Best way to get latest version)
@@ -57,10 +55,10 @@ public class Spawner : MonoBehaviour
57
55
58
56
public void Spawn ()
59
57
{
60
- _prefab .Get (transform .position , transform .rotation );
58
+ _prefab .Reuse (transform .position , transform .rotation );
61
59
62
60
// 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 ;
64
62
}
65
63
}
66
64
```
@@ -76,7 +74,7 @@ public class Spawner : MonoBehaviour
76
74
77
75
public void Spawn ()
78
76
{
79
- var instance = _prefab .Get (transform .position , transform .rotation );
77
+ var instance = _prefab .Reuse (transform .position , transform .rotation );
80
78
instance .Release ();
81
79
}
82
80
}
@@ -94,29 +92,26 @@ public class Health : MonoBehaviour, IPoolable
94
92
private float _health = 0 f ;
95
93
96
94
// Awake will be called on first _prefab.Get()
97
- private void Awake () =>
98
- OnGet ();
95
+ private void Awake ()
96
+ {
97
+ OnReuse ();
98
+ }
99
99
100
100
// 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
+ {
103
107
_health = _maxHealth ;
108
+ }
104
109
105
110
// IPoolable method
106
111
public void OnRelease () { }
107
112
}
108
113
```
109
114
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
-
120
115
### Peformance test:
121
116
Creating and destroying 1000 objects.
122
117
@@ -175,7 +170,7 @@ public class Tester : MonoBehaviour
175
170
176
171
for (int i = 0 ; i < 1000 ; i ++ )
177
172
{
178
- var instance = _object .Get ();
173
+ var instance = _object .Reuse ();
179
174
instance .Release ();
180
175
}
181
176
0 commit comments