Why does this print '0'?

Code:

local players = game:GetService("Players"):GetPlayers()
print(#players)

Output:
0

Addit. Info:

  • Being called from a ModuleScript
  • I’m using this for a random player picker
1 Like

That means there are zero players currently in the game.
Players:GetPlayers() returns a table with all the players, and putting a # in front of it would get the length of the table.

If there were 2 players: e.g recanman and builderman, that would print 2.
Read more here: Players | Documentation - Roblox Creator Hub

1 Like

The problem is that I am in the server, so it should print 1. However, it still prints 0.

Since you are most5 likely using Play, the scripts run before your player actually joins, so you should add a delay to it.

2 Likes

The code could possibly be getting run before your player has actually loaded into the game

1 Like

Yup, forgot about that. Thanks for the reminder! (It works now)

You can connect this to a PlayerAdded event so it runs when an actual player joins the game, similar to what @recanman and @Synthetic_Flame said.

game.Players.PlayerAdded:Connect(function(Player)
    local players = game:GetService("Players"):GetPlayers()
    print(#players)
end)