I am trying to make a script that constantly has the amount of players at a set place, but I can't get my script to work.
_G.numberOfPlayers = 0 local players = game.Players for I, v in pairs(players:GetChildren()) do wait(.01) if v.Backpack.isPlaying.Value == true then _G.numberOfPlayers = _G.numberOfPlayers + 1 end _G.numberOfPlayers = 0 end
Other scripts can only run when this script is yielded (that is, it has called a wait
command and not returned yet). Thus, you should set numberOfPlayers
to 0 before updating its value. You should write your loop like this:
local players = game.Players local isPlaying while true do _G.numberOfPlayers = 0 for i, player in ipairs(players:GetPlayers()) do isPlaying = v.Backpack:FindFirstChild("isPlaying") if isPlaying and isPlaying.Value then _G.numberOfPlayers = _G.numberOfPlayers + 1 end end wait() end
Notes:
wait(.01)
is no less waiting than around wait(.025)
, so you might as well just do wait()
wait()
after fully updating numberOfPlayers
, not during. As you can see, you need a while
loop to continuously update the numberOfPlayers
value.== true
in an if
statement unless you need to differentiate between non-false/nil values. In Lua, everything that isn't false/nil evaluates to true and that's all it takes for an if
statement to run.isPlaying
will always be in the backpack, but - just to make sure - I used FindFirstChild
so that your script won't error and then stop functioning.It doesn't matter with such a small loop, but in general it is better to use events to maintain values (rather than a while true do
loop). In this case, the events you'd need would be these:
numberOfPlayers
numberOfPlayers
numberOfPlayers
Again, the above script is simpler and not significantly less efficient.