I've tried a bunch of ideas to give my code an accurate player count, but so far, nothing has worked out. The piece of code that's gotten me closest looks something like this - 'val' being a number variable that stores the number of players. I've set it up so that it checks every .15 seconds.
while true do wait(0.15) game.Players.PlayerAdded(function(player) val.Value = val.Value + 1 end) game.Players.PlayerRemoving(function(player) val.Value = val.Value - 1 end end)
This code works in simple tests, but on a real server, it ends up adding/removing over 100 to the value instead of just one. Is there a more simple way I could get the number of players currently on the server. Any answers are greatly appreciated.
You can use the
:GetChildren() function and the # operator to get how much players are ingame. The # returns the length of a table and
:GetPlayers() returns a array, which is a table.
local players = game.Players:GetPlayers() -- getting players val.Value = #players -- the value will show the length of the table
If you want to get player count, just do this:
local playerCount = #game.Players:GetPlayers()
Next time you have a problem like this, I suggest you search up the problem yourself as simple things like these often have simple solutions. Nonetheless, I will show you what you were doing wrong in your method (for the sake of learning).
The problem with your method is that
while loops aren't needed here. I suggest you read up on
RBXScriptSignals. Events fire whenever a particular occurrence happens in the game (in this case a player joining/leaving). There is only need to connect them once. Here's the correct code:
game.Players.PlayerAdded:Connect(function(player) val.Value = val.Value + 1 end) game.Players.PlayerRemoving:Connect(function(player) val.Value = val.Value - 1 end)
Easy fix: create a variable, add the variable every time a player is detected...
local players = game.Players:GetChildren() -- list of players local player_count = 0 -- currently 0 players while wait(1) do -- updater for i, player in pairs(players) do -- loop to get players player_count = player_count + 1 -- add every player detected. print("There are "..i.." players in the game") -- print how many players end end
This is I guess easy to read but the other questions are better, don't read this it is just another way if those other codes don't work..