I’ve been wanting my code to properly spawn a specific number of NPCs or enemies after each wave. It works, but not in the way I expect it to.
For example:
It spawns 4 NPCs each wave (originally it spawned more when I had originally set a line of code to multiply the amount each wave), but the amount of them is supposed to be two only. I have tried removing the multiplying part in a line, or try changing the method of how many there’s supposed to be, though that doesn’t seem to improve it at all.
I don’t know why, but I’d really like to know how I can solve this issue.
Here’s the script:
-- Events
local ServerStorage = game:GetService("ServerStorage")
-- Variables
local EnemiesFolder = game.Workspace:WaitForChild("Enemies")
local EnemiesAlive = EnemiesFolder.EnemiesAlive
local telePart = game.Workspace:WaitForChild("TestPart")
local NPC = ServerStorage:FindFirstChild("NPC")
local spawnTime = 3
-- Constants
local waves = 10
-- Function to handle NPC spawning
local function spawnEnemy(quantity)
if not NPC then
warn("No NPC in ServerStorage!")
return
end
for i = 1, quantity do
local enemy = NPC:Clone()
-- random offset to prevent stacking
local randomOffset = Vector3.new(math.random(-5, 5), 0, math.random(-5, 5))
enemy.HumanoidRootPart.Position = telePart.Position + randomOffset
enemy.Parent = workspace.Enemies
print("Enemy spawned")
end
end
-- Function to handle wave settings
local function spawnWave(waveNum, enemyAmount, spawnDelay)
local waveCount = 1
for waveCount = 1, waveNum do
task.wait(3)
print("Wave " ..waveCount.. " started")
for i = 1, enemyAmount do
task.wait(spawnDelay)
spawnEnemy(enemyAmount)
end
repeat
task.wait()
until EnemiesAlive.Value == 0
print("Wave " ..waveCount.. " ended")
end
end
-- Function to start the wave
local function startWave(totalWaves, enemyCount, SpawnDelay)
spawnWave(totalWaves, enemyCount, SpawnDelay)
end
startWave(waves, 2, spawnTime)