@@ -13,6 +13,7 @@ public class Pool
13
13
14
14
private Queue < Poolable > entities = null ;
15
15
private bool isFilled = false ;
16
+ private int currentCount = 0 ;
16
17
17
18
public Pool ( Poolable prefab , int startCount , bool isResizable , Transform holder )
18
19
{
@@ -28,6 +29,7 @@ public void Fill()
28
29
return ;
29
30
30
31
entities = new Queue < Poolable > ( startCount ) ;
32
+ currentCount = startCount ;
31
33
32
34
for ( int i = 0 ; i < startCount ; i ++ )
33
35
{
@@ -44,6 +46,9 @@ public Poolable GetEntity()
44
46
{
45
47
Poolable entity = TakeEntity ( ) ;
46
48
49
+ if ( IsEmpty ( entity ) )
50
+ return null ;
51
+
47
52
entity . ReturnFromPool ( ) ;
48
53
49
54
return entity ;
@@ -53,6 +58,9 @@ public Poolable GetEntity(Transform parent, bool spawnInWorldSpace)
53
58
{
54
59
Poolable entity = TakeEntity ( ) ;
55
60
61
+ if ( IsEmpty ( entity ) )
62
+ return null ;
63
+
56
64
entity . transform . SetParent ( parent , spawnInWorldSpace ) ;
57
65
entity . ReturnFromPool ( ) ;
58
66
@@ -63,6 +71,9 @@ public Poolable GetEntity(Vector3 position, Quaternion rotation)
63
71
{
64
72
Poolable entity = TakeEntity ( ) ;
65
73
74
+ if ( IsEmpty ( entity ) )
75
+ return null ;
76
+
66
77
entity . transform . SetPositionAndRotation ( position , rotation ) ;
67
78
entity . ReturnFromPool ( ) ;
68
79
@@ -72,6 +83,10 @@ public Poolable GetEntity(Vector3 position, Quaternion rotation)
72
83
public Poolable GetEntity ( Vector3 position , Quaternion rotation , Transform parent , bool spawnInWorldSpace )
73
84
{
74
85
Poolable entity = TakeEntity ( ) ;
86
+
87
+ if ( IsEmpty ( entity ) )
88
+ return null ;
89
+
75
90
Transform entityTransform = entity . transform ;
76
91
77
92
entityTransform . SetParent ( parent , spawnInWorldSpace ) ;
@@ -87,6 +102,7 @@ public void ReturnEntity(Poolable entity)
87
102
return ;
88
103
89
104
entities . Enqueue ( entity ) ;
105
+ currentCount ++ ;
90
106
91
107
entity . transform . SetParent ( holder , false ) ;
92
108
entity . gameObject . SetActive ( false ) ;
@@ -99,7 +115,7 @@ private Poolable TakeEntity()
99
115
100
116
Poolable entity ;
101
117
102
- if ( entities . Count == 0 )
118
+ if ( currentCount == 0 )
103
119
{
104
120
if ( isResizable )
105
121
{
@@ -119,11 +135,15 @@ private Poolable TakeEntity()
119
135
{
120
136
entity = Object . Instantiate ( prefab , holder ) ;
121
137
entity . SetPool ( this ) ;
138
+ currentCount ++ ;
122
139
}
123
140
124
141
entity . gameObject . SetActive ( true ) ;
142
+ currentCount -- ;
125
143
126
144
return entity ;
127
145
}
146
+
147
+ private bool IsEmpty ( Poolable entity ) => ! isResizable && entity == null ;
128
148
}
129
149
}
0 commit comments