Reviewing my NPC spawner

Please be advised that this is literally a 15 minute throw-together-script; I do plan to advance it at a later date.

The way this script works is by: Spawning Enemies / Hostiles / ETC. ServerSide in accordance to the Player(s) distance from the ‘Spawners’.

local Players = game:GetService("Players")
local SpawnPoints = game:GetService("Workspace")["SpawnPoints"]

local Points = {}
for _,i in pairs (SpawnPoints:GetDescendants()) do
	if i:IsA("BasePart") and i.Name == "Point" then
		table.insert(Points, i)
	end
end

spawn(function()
	while true do wait(.15)
		for _,i in pairs (Players:GetPlayers()) do
			if i.Character ~= nil then
				for _,p in pairs (Points) do
					if (i.Character["HumanoidRootPart"].Position - p.Position).Magnitude < 15 then
						isSpawn(i, p)
					else
					end
				end
			end
		end
	end
end)

function isSpawn(i, p)
	local z = p:GetChildren()
	if #z > 0 then
		print("Found!")
		repeat wait()
		if p:FindFirstChild("Bandit") ~= nil then
			if (i.Character["HumanoidRootPart"].Position - p["Bandit"]["HumanoidRootPart"].Position).Magnitude > 50 then
				p["Bandit"]:Destroy()
			end
		end
		until p:FindFirstChild("Bandit") == nil
		return
	else
		local NPC = script["Bandit"]:Clone()
		NPC.Parent = p
		NPC:MoveTo(p.Position + Vector3.new(0, 3, 0))
		NPC["isFollow"].Disabled = false
		return
	end
end
2 Likes

It appears fine but you could easily remove that never ending loop for something like Zone+ so it runs off an event instead. My main issue with this is actually your variables and lack of comments than performant, For instance:

You’re using i to represent both player and spawnpoints in two seperate areas.
You’re also using p and z to represent spawnpoints.

This is just plain confusing and then you don’t use any comments to summarize each section.

Aside this your following code doesn’t look particually performant as it’s constantly looping until Bandit is within the players model. While I understand the inclination to do this, it’s best to use events where possible so when you insert Bandit into the Model you should fire an event or similar to let the script know.

That said it’s generally okay but you may want to look into both using events over loops where possible and into Human Code [DevForum Post Linked].

2 Likes

Thank you! Could you define what functions I could use to replace the loops and get the distance between Players and SpawnPoints

Zone+ is a great little module.

1 Like