For loop keeps repeating

Hello! I have made a for loop that loops through the players and teleports them as well as a few other things. But it keeps repeating every 10 seconds or so, and I am very confused.

Code, in ServerScriptService:

local players = game:GetService("Players")
local amount = #players:GetPlayers()
local status = game.ReplicatedStorage.StatusValue
plrready = 0

players.PlayerAdded:Connect(function(player)
	amount = amount + 1
end)

players.PlayerRemoving:Connect(function()
	amount = amount - 1
end)

while true do
	wait()
	print(amount)
	if amount >= 2 then
		game.ReplicatedStorage.StatusValue.Value = "players found, starting game momentarily"
		wait(15)
		for i, v in pairs(game.Players:GetChildren()) do
			if v.InGame.Value == false then
				game.ReplicatedStorage.GameStartEvent:FireClient(v)
				v.PlayerGui.TextGui.Enabled = true
				v.InGame.Value = true
				v.Character:FindFirstChild("HumanoidRootPart").CFrame = game.Workspace.TeleportPart.CFrame
				v.InGame.Value = true
			end
		end
		status.Value = "investigate the area"
		wait(100)
	else
		game.ReplicatedStorage.StatusValue.Value = "waiting for more players"
		wait(.5)
		game.ReplicatedStorage.StatusValue.Value = "waiting for more players."
		wait(.5)
		game.ReplicatedStorage.StatusValue.Value = "waiting for more players.."
		wait(.5)
		game.ReplicatedStorage.StatusValue.Value = "waiting for more players..."
		wait(.5)
	end
end

Does anyone know why this happens? Thank you and happy holidays! :santa:

1 Like

have you tried breaking the loop with a conditional statement and break?

2 Likes

I don’t really see why you update amount manually. You can just add it inside the while loop as a variable.

while true do
   wait()
   local amount = #players:GetPlayers()
   print(amount)
   -- the rest of your code
end
2 Likes

Thank you, but would that fix my issue?

2 Likes

But I want the loop to start again once the game ends, could I still do that?

1 Like

write the loop in a function and call upon the function when you need it

1 Like

Okay, so I call the function, and once the loop ends it breaks, and goes to another function? Where would I put the break, inside the loop or outside? Because any code outside the loop won’t run for some reason. It just repeats the loop constantly.

1 Like

It could. It’s always best to try. After all, to teleport you’re checking the current amount of players.

1 Like

Alright, I did that. The code still works, much cleaner, thank you.

But the loop problem is still there.

2 Likes

I added a break in the look and it works! Thank you so much.