Is it possible to see how many players are playing in your server right now, in a script?
I already see an answer on the question but it doesn't give a comprehensive explanation on how it works.
How to see how many players there are in your server?
Get the length of an array generated from :GetPlayers()
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.
: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.
Output the length of myTable
local myTable = { "apple", "pear", "banana" } local lengthOfMyTable = #myTable print(lengthOfMyTable)
With an output of:
3
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
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())