NumPlayers returns as 0, even when I join the server

I’ve tried both -

local NumPlayers = #game.Players:GetPlayers()


local NumPlayers = game.Players.NumPlayers

Yet they both return “0”

If it gives any better info, i’m making a round-based game and i’m not understanding the reasoning for this happening?

1 Like

I recommend adding a wait statement, have you also tried a for i,v statement, and having a value to keep the number of players there? What I just said isn’t efficient, but if what you just did didn’t work, I recommend to try new methods, or keep trying to get what you listed to work.

1 Like

Yeah, the wait worked for me.

Thanks, chap!

1 Like

When you store something in a variable it keeps a reference to that value. It does not update on it’s own.

Here is an example of something you could do:

local Players = game:GetService("Players")
local NumPlayers = Players.NumPlayers -- Will always be the initial NumPlayers value (most likely 0 unless the script ran after you joined) unless set again
someCallbackOrEvent:Connect(function() -- Could be at any time
	print(Players.NumPlayers) -- Will always be up to date.

I would also recommend not using wait to fix your problems. If you’re using wait anywhere besides permanent game loops (e.g. game ticks) or places where timing is involved (e.g. round timers) it’s probably a sign you’re not doing something the way it should be done.

(I’d recommend using game:GetService(“Players”) btw)

Yeah, it doesn’t seem very efficient, but it works.

For efficiency though, i’m either just not going to store it in a variable as it’s easy to get or have an updating feature.

Why store it in a variable at all? And if you really want a variable you can connect events to Players.PlayerAdded and Players.PlayerRemoving which will update your variable.

Yeah, I already got rid of the var.

Thanks for the help, bro.

No problem! Good luck on your game :smile:

#game.Players:GetPlayers() will always return the current amount of players in the game. If the variable you assigned to it is returning 0 and there are people in the game, then your code’s logic must be messing up somewhere.

Don’t do this. This is bad for two reasons:

  1. This can lead to race conditions
  2. wait() isn’t guaranteed to actually wait for 1/30th of a second. (For more info, see @Kampfkarren’s thread : Avoiding wait() and why)

This would make no difference.

local NumPlayers=#game.Players:GetPlayers()

is the same as

local NumPlayers=0
for i,v in pairs(game.Players:GetPlayers()) do

Yeah, so, I ended up going with not using a variable, there’s no up upside to it.

Thanks for the help.