Random spawning NPCs script

I’m adding randomly spawning soldier NPCs in my Tycoon, and for that I made the script below to spawn them randomly on parts that I scattered throughout the map. I also included a maximum of them that can be spawned at any time (and deduct that if one dies; other script) and configurations.

local Spawns = workspace:WaitForChild("NPCSpawns"):GetChildren()
local NPC = game.ServerStorage.Soldier
local amount = script.Amount

wait(20)
while true do
	if amount.Value < 20 then
		wait(math.random(45,75))
		local NPCs = NPC:Clone()
		local config = NPCs.Configuration
		config.AttackDamage.Value = math.random(8,12)
		config.AttackDelay.Value = math.random(70,80)*0.01
		config.AttackRadius.Value = math.random(110,130)
		config.PatrolRadius.Value = math.random(300,500)
		NPCs:PivotTo(Spawns[math.random(#Spawns)].CFrame)
		amount.Value += 1
		NPCs.Parent = workspace.NPCs
	else
		wait(5)
	end
end

Now, this all works fine and dandy, but I believe the scripting is extremely ugly (I whipped this out of my own knowledge, which isn’t that much). I think something with coroutines or the spawn function can tidy it up, but I’m not at all sure how to do that. I did find some posts regarding those, and I checked the wiki, but I could not figure out how to implement it.

Also, this is my first post here (just found out I could even post, wasn’t able to for a long time), so I hope this is an appropriate post and question.

1 Like

It is quite good code. I am not that sure how else you could change this to make it more efficient. I am not really sure at all how you could change this really.

1 Like

task.wait() instead of wait() would be my only feedback.

1 Like

Thank you both! I really thought there would be a cleaner way to do this, but I guess I wrote it right.
And I had no idea task.wait() existed, thank you for giving me that knowledge :slight_smile: I just found heartbeat to be too complex and didn’t bother too much reading into that, but I will now go over my code and do some benchmarking!

I have improved my spawning method a bit, you don’t actually need an extra variable to count the current NPCs, as you can you count the children and use that. I have also put in the task.wait() to improve the intented spawning time.

local Spawns = workspace:WaitForChild("NPCSpawns"):GetChildren()
local NPC = game.ServerStorage.Soldier

while true do
	local children = workspace:WaitForChild("NPCs"):GetChildren()
	local count = #children
	if count < 16 then
		wait(math.random(40,60))
		local NPCs = NPC:Clone()
		local config = NPCs.Configuration
		config.HealthAmount.Value = math.random(90,100)
		config.AttackDamage.Value = math.random(8,12)
		config.AttackDelay.Value = math.random(70,85)*0.01
		config.AttackRadius.Value = math.random(100,120)
		config.PatrolRadius.Value = math.random(175,250)
		NPCs:PivotTo(Spawns[math.random(#Spawns)].CFrame)
		NPCs.Parent = workspace.NPCs
	else
		task.wait()
	end
end