boolValue not changing

Hi. So my script is meant to check how many players there are. For testing purposes, I made it so if it is less than 1, then the scripts dont run and a boolValue is set to false. However, the BoolValue isn’t changing when there is 1 or more players. I’m not really sure what’s wrong, here’s the script.

local ss = game.ServerScriptService
local rsr = game.ReplicatedStorage.Round


while wait() do
	playerCount = #game.Players:GetPlayers()
end

game.Players.PlayerAdded:Connect(function(player)
	if playerCount < 1 then
		game.ReplicatedStorage:WaitForChild("WillRun").Value = false 
		ss.inter.Disabled = true
		ss.round2.Disabled = true
		rsr.Intermission.Value = 10
		rsr.InRound.Value = false
		rsr.spawner.Value = 1
		for _,v in ipairs(game.Players:GetPlayers()) do
			v:LoadCharacter()
		end
	else
		game.ReplicatedStorage.WillRun.Value = true
		ss.inter.Disabled = false
		ss.round2.Disabled = false
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	if playerCount < 1 then
		game.ReplicatedStorage.WillRun.Value = false 
		ss.inter.Disabled = true
		ss.round2.Disabled = true
		rsr.Intermission.Value = 10
		rsr.InRound.Value = false
		rsr.spawner.Value = 1
		for _,v in ipairs(game.Players:GetPlayers()) do
			v:LoadCharacter()
		end
	else
		game.ReplicatedStorage.WillRun.Value = true
		ss.inter.Disabled = false
		ss.round2.Disabled = false
	end
end)

This loop is causing the issue. With while loops, they yield and prevent code below it from running until it is broken. The way to stop this is to put it at the very end of the script

Found the issue. The code ran too fast, so playerCount returned nil.

This is using up lots of performance, do not use this in any work whatsoever.

A more faster alternative is to use the Players.PlayerAdded event to update the value:

function setPlayerCount() playerCount = #game.Players:GetPlayers() end

game.Players.PlayerAdded:Connect(setPlayerCount)
game.Players.PlayerRemoving:Connect(setPlayerCount)
1 Like

Even if it’s “too fast” or has some sort of delay, do not use loops to update the value. An event that runs every time a player joins or leaves is much better.

Yeah, I know. I just used the while loop to make sure it wasn’t getting the playerCount wrong somehow.

How could it possibly go wrong? The value updates literally when the amount of players changes.

Yeah, I tried it before and it didn’t work because it also ran too fast. I added a wait(0.2) now though.

Since you already solved it, I’ll leave this forum post alone, but try not to use loops anyway. There’s always a better solution than loops.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.