Skip to content

Commit e872a9d

Browse files
authored
Optimization
1 parent c705dff commit e872a9d

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

Pool.cs

+21-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public class Pool
1313

1414
private Queue<Poolable> entities = null;
1515
private bool isFilled = false;
16+
private int currentCount = 0;
1617

1718
public Pool(Poolable prefab, int startCount, bool isResizable, Transform holder)
1819
{
@@ -28,6 +29,7 @@ public void Fill()
2829
return;
2930

3031
entities = new Queue<Poolable>(startCount);
32+
currentCount = startCount;
3133

3234
for (int i = 0; i < startCount; i++)
3335
{
@@ -44,6 +46,9 @@ public Poolable GetEntity()
4446
{
4547
Poolable entity = TakeEntity();
4648

49+
if (IsEmpty(entity))
50+
return null;
51+
4752
entity.ReturnFromPool();
4853

4954
return entity;
@@ -53,6 +58,9 @@ public Poolable GetEntity(Transform parent, bool spawnInWorldSpace)
5358
{
5459
Poolable entity = TakeEntity();
5560

61+
if (IsEmpty(entity))
62+
return null;
63+
5664
entity.transform.SetParent(parent, spawnInWorldSpace);
5765
entity.ReturnFromPool();
5866

@@ -63,6 +71,9 @@ public Poolable GetEntity(Vector3 position, Quaternion rotation)
6371
{
6472
Poolable entity = TakeEntity();
6573

74+
if (IsEmpty(entity))
75+
return null;
76+
6677
entity.transform.SetPositionAndRotation(position, rotation);
6778
entity.ReturnFromPool();
6879

@@ -72,6 +83,10 @@ public Poolable GetEntity(Vector3 position, Quaternion rotation)
7283
public Poolable GetEntity(Vector3 position, Quaternion rotation, Transform parent, bool spawnInWorldSpace)
7384
{
7485
Poolable entity = TakeEntity();
86+
87+
if (IsEmpty(entity))
88+
return null;
89+
7590
Transform entityTransform = entity.transform;
7691

7792
entityTransform.SetParent(parent, spawnInWorldSpace);
@@ -87,6 +102,7 @@ public void ReturnEntity(Poolable entity)
87102
return;
88103

89104
entities.Enqueue(entity);
105+
currentCount++;
90106

91107
entity.transform.SetParent(holder, false);
92108
entity.gameObject.SetActive(false);
@@ -99,7 +115,7 @@ private Poolable TakeEntity()
99115

100116
Poolable entity;
101117

102-
if (entities.Count == 0)
118+
if (currentCount == 0)
103119
{
104120
if (isResizable)
105121
{
@@ -119,11 +135,15 @@ private Poolable TakeEntity()
119135
{
120136
entity = Object.Instantiate(prefab, holder);
121137
entity.SetPool(this);
138+
currentCount++;
122139
}
123140

124141
entity.gameObject.SetActive(true);
142+
currentCount--;
125143

126144
return entity;
127145
}
146+
147+
private bool IsEmpty(Poolable entity) => !isResizable && entity == null;
128148
}
129149
}

0 commit comments

Comments
 (0)