Help with NPC spawning at night time script

I was working on a way to make NPCs spawn at night, and then they die in order , but it wasn’t working as intended. The NPCs spawn incredibly fast, and they don’t despawn in the day time.


Server script located in ServerScriptService.

local lighting = game:GetService("Lighting")

lighting:GetPropertyChangedSignal("ClockTime"):Connect(function()
	if lighting:GetMinutesAfterMidnight() > 1080 then
		print("Day")
		for i,v in pairs(workspace.NightTimeNpcs:GetDescendants()) do
			if v ~= nil then
				if v:IsA("Humanoid") then
					v.Health = 0
					wait(2)
					v.Parent:Destroy()
					wait(1)
				end
			end
		end
	elseif lighting:GetMinutesAfterMidnight() < 360 then
		print("Night")
		spawn(function()
			for i = 1,5 do
				local Part = game.Workspace.GeneratePart

				local NPCs = game.ServerStorage.NightTimeNpcs:GetChildren()
				local NPCnumber = #NPCs
				
				local Speed = NPCs[math.random(1,#NPCs)]:Clone()

				Speed.HumanoidRootPart.CFrame = Part.CFrame * CFrame.new(math.random(-Part.Size.X/2, Part.Size.X/2),math.random(-Part.Size.Y/2, Part.Size.Y/2),math.random(-Part.Size.Z/2, Part.Size.Z/2))
				Speed.Parent = workspace.NightTimeNpcs
				wait(15)
				if lighting.ClockTime > 6 and lighting.ClockTime < 18 then
					break
				end
			end
		end)	
	end
end)

Any help is appreciated!

2 Likes

Instead of 1080, try 360. As for the fast npc spawning, I think it’s because the event is fired every second. You can add a debounce to fix this. Hope this helps.

1 Like

Probably you have a script that changes time too quickly so the function gets called repeatedly. Also v~= nil is a completely useless statement + instead of using getdescedants try using getchildren and then if v:FindFirstChild(“Humanoid”) then. In addition i dont see any use for the variable NPCnumber.

1 Like

The reason it is there was for something else, I ended up not needing it, but I forgot to remove the variable. Also the reason why I was doing this:

           if v ~= nil then
				if v:IsA("Humanoid") then
					v.Health = 0
					wait(2)
					v.Parent:Destroy()
					wait(1)
				end
			end

instead of:

if v:FindFirstChild("Humanoid") then
				v.Humanoid.Health = 0
				wait(2)
				v:Destroy()
				wait(1)
			end

Is because I changed the name of the humanoid inside of the monsters to “MonsterHumanoid”, so that monsters won’t attack each other, but I want some special wandering NPCs to spawn at night time too, but I want them to be able to get attacked by monsters. I can do this:

for i,v in pairs(workspace.NightTimeNpcs:GetChildren()) do
			if v:FindFirstChild("MonsterHumanoid") or v:FindFirstChild("Humanoid") then

But it just makes it killing the NPCs a lot harder. If I want another group of monsters to have a different name for the humanoid that isn’t “Humanoid” nor “MonsterHumanoid”, I will have to add that to the if statement.