Skip to content

Commit 093ef6d

Browse files
committed
Fix spawn logic when recycling
1 parent 1506734 commit 093ef6d

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

Assets/Scripts/ObjectSpawner.cs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
using System;
1212
using System.Collections.Generic;
1313
using UnityEngine;
14+
using UnityEngine.Assertions;
1415
using UnityEngine.SceneManagement;
1516

1617
namespace Supyrb
@@ -41,6 +42,7 @@ public float SpawnCoolDownSeconds
4142
get => spawnCoolDownSeconds;
4243
set
4344
{
45+
Assert.IsTrue(value > 0, $"Spawn cooldown needs to be greater than 0, but was set to {value}");
4446
spawnTimeBase += (spawnCoolDownSeconds - value) * totalSpawnCount;
4547
spawnCoolDownSeconds = value;
4648
}
@@ -79,7 +81,8 @@ private void Awake()
7981
private void Update()
8082
{
8183
float relativeSpawnTime = Time.time - spawnTimeBase;
82-
if (Mathf.FloorToInt(relativeSpawnTime / spawnCoolDownSeconds) > totalSpawnCount)
84+
int itemsToSpawn = Mathf.FloorToInt(relativeSpawnTime / spawnCoolDownSeconds) - totalSpawnCount;
85+
for(int i = 0; i < itemsToSpawn; i++)
8386
{
8487
SpawnObject();
8588
}
@@ -102,13 +105,7 @@ private void SpawnObject()
102105
if (spawnedObjects.Count >= maxInstances)
103106
{
104107
var recycleGo = spawnedObjects.Dequeue();
105-
if(recycleGo == null)
106-
{
107-
// If the spawned object was destroyed, we create a new one
108-
// Decrement spawn count since it will be incremented when created below
109-
totalSpawnCount--;
110-
}
111-
else
108+
if(recycleGo != null)
112109
{
113110
#if UNITY_2021_3_OR_NEWER
114111
recycleGo.transform.SetLocalPositionAndRotation(transform.position, transform.localRotation);
@@ -117,6 +114,7 @@ private void SpawnObject()
117114
recycleGo.transform.localRotation = transform.localRotation;
118115
#endif
119116
spawnedObjects.Enqueue(recycleGo);
117+
totalSpawnCount++;
120118
return;
121119
}
122120
}

0 commit comments

Comments
 (0)