Is it possible to see how many players are playing in your server right now, in a script?
How to see how many players there are in your server?
2 answers
Note
I already see an answer on the question but it doesn't give a comprehensive explanation on how it works.
Question
How to see how many players there are in your server?
Answer
Short Answer
Get the length of an array generated from :GetPlayers()
Long Answer
To start off, we should look at the API documentation for the Players service
A look at that will reveal the :GetPlayers() method which returns an array containing all of the players that are in game.
Example of using :GetPlayers()
Get all the ingame players and output their names
local players = game:GetService("Players")
local playersIngame = players:GetPlayers()
for i, player in pairs(playersIngame) do
print(player.Name)
end
The number of players in the game will be the length of the array. How do we get the length of an array? you may ask. You can use the # operator which when invoked on a table will return the length of the table.
Example of Length Operator
Output the length of myTable
local myTable = {
"apple",
"pear",
"banana"
}
local lengthOfMyTable = #myTable
print(lengthOfMyTable)
With an output of:
3
The Final Product
local players = game:GetService("Players") --// define players service
local playersIngame = players:GetPlayers() --// get the players ingame
local numberOfPlayers = #playersIngame --// get the length of the array containing the players
print(numberOfPlayers) --// output the length which is how many players are ingame
Reading Resources:
https://developer.roblox.com/en-us/api-reference/function/Players/GetPlayers
https://en.wikibooks.org/wiki/Lua_Programming/length_operator
https://developer.roblox.com/en-us/api-reference/function/ServiceProvider/GetService
Do this to get how many players there are in a server.
print(#game.Players:GetPlayers())
This discussion is preserved as it was. New answers, comments, and votes are closed.
