Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Best way to lower the counter in this NPC cloner script when a child gets removed?

wait(5)
local child = game.workspace.Spawn.ChildAdded:Connect(function(child)
	
end)

local ZombieCount = 0 --Supposed to cap the zombies

local NPC = game.ReplicatedStorage.ZombieStorage.Zombies.Zombie

local spawner = game.workspace.Spawn --The spawning brick

local children = game.workspace.Spawn:GetChildren()

while ZombieCount <5 do
	local Clone = NPC:Clone()
	Clone.Parent = spawner
	Clone.Torso.CFrame = spawner.CFrame --Spawns the zombie where the brick is
		wait(0.05)
	if child then ZombieCount = ZombieCount +1 --Counter that keeps track of zombies
	end
end

--Need a way to lower the count on death

I need this count to lower so another NPC can spawn after one dies, but I haven't figured out how to do it after toiling with the script for a while.

I've tried:

if Clone.ChildRemoved then ZombieCount = ZombieCount -1 --the zombies just infinitely spawn


elseif Clone.ChildRemoved then ZombieCount = Zombiecount -1 --nothing happens when they die

if spawner.ChildRemoved then ZombieCount = Zombiecount -1 -- infinite spawns again

if spawner.ChildRemoved == true then ZombieCount = Zombiecount -1 --nothing happens when they die

if Clone.Humanoid.Died == true then ZombieCount = Zombiecount -1 --nothing happens when they die

Does the while do script just permanently end when they hit the cap? Should I be calling on all of the children? I've looked around and can't figure out what I should be calling/the correct event to call (if there is one).

1 answer

✓ Accepted answer

for the while loop you could do

while wait() do
	if #spawner:GetChildren() < 5 then
	    local Clone = NPC:Clone()
	    Clone.Parent = spawner
	    Clone.Torso.CFrame = spawner.CFrame
	end
end

explanation for this would be

loop that spawns an npc and puts it in the spawner if the number of npcs inside the spawner is less than five.

this is also assuming that the spawner doesn't have anything except for the npcs the zombiecount variable would be redundant though

1 comment

0

Thanks mate, I knew there was a way but I just couldn't figure it out, I didn't know you could do #. As for the zombiecount, that is there because there are a lot of different zombie NPCs that do take up the spawner, but I can likely combine them all into one big script and just do some math.randoms to determine which one spawns now instead of the annoying cap system from before!

This discussion is preserved as it was. New answers, comments, and votes are closed.