Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I rest the while loop?

Asked by 3 years ago

I have a script that spawns a random NPC from a folder onto a random block that is in another folder. I set a max number of 5 so no more than 5 NPCs will spawn. But how do I set it so they respawn once one dies. Or How do I rest the code once all spawned NPCs have died.

local NPCS = game.ReplicatedStorage.Enemies:GetChildren()
local number = 0

if number >= 0 then
        canspawn = true
        print("can spawn")
    end 
while  canspawn do
    local ChosenNPC = NPCS[math.random(1, #NPCS)]
    local ChosenSpawn = math.random(1, 6)
    print(ChosenNPC)
    print(ChosenSpawn)
    wait(5)
    if ChosenNPC then
    clone = ChosenNPC:Clone()
        number = number + 1     
        print(number)

        clone.HumanoidRootPart.Position = workspace.EnemySpawns:FindFirstChild("Spawn"..ChosenSpawn).Position
        clone.Parent = workspace.EnemySpawns.Spawned
        clone:MakeJoints()
        if number >= 5 then
            canspawn = false
            print("Stoping spawning")
        end 



    end

end

1 answer

Log in to vote
0
Answered by
BiIinear 104
3 years ago

Stop the loop with break.

while canspawn do

    if number >= 5 then

        canspawn = false
        break
    end
end

If you ever want to activate the loop again, put the loop into a function.

Example:

function loop()
    while true do

    end
end

loop() -- activates the loop
0
Thanks for the tip Boss246813579 -6 — 3y
Ad

Answer this question