Can't get the amount of players in game

While trying to make a round system, I want to ensure that there are at least 2 players in game or more. When running my script, the script keeps telling me there are 0 players in game but there are 2. I am testing this using the studio multi player testing server.

-- Variables

local InRound = workspace.InRound
local Players = game:GetService("Players")
local NPlayers = #game:GetService("Players"):GetPlayers()
local MinPlayers = 2
local ValidPlay = false

local RoundTime = 540
local WaitTime = 30

-- Functions

local function RunRound()
	game:GetService("ReplicatedStorage").BeginRound:FireAllClients()
	while wait(1) do
		RoundTime -= 1
		game:GetService("ReplicatedStorage").UpdateRoundTime:FireAllClients(RoundTime)

		if RoundTime <= 0 then
			game:GetService("ReplicatedStorage").FinishRound:FireAllClients()

			wait(3)

			while wait(1) do
				WaitTime -= 1
				game:GetService("ReplicatedStorage").UpdateRoundTime:FireAllClients()

				if WaitTime <= 0 then
					InRound = false
					break
				end
			end
			break
		end
	end
end

-- Check players

while wait(5) do
	if NPlayers >= MinPlayers then
		print("Starting...")
		ValidPlay = true
		break
	else
		print("False")
		ValidPlay = false
		print(tostring(NPlayers))
	end
end

if ValidPlay == true then
	RunRound()
	InRound = true
end

InRound.Changed:Connect(function()
	if InRound.Value == false then
		RunRound()
		InRound = true
	end
end)

Can someone help?

It’s because you check the number of players at the start of the script rather than when you need to.

I recommend instead of using the NPlayers, you have a variable that stores the Players service, and then when you need to get the amount of players, get the amount of players there

Example,

Instead of

if NPlayers >= MinPlayers then

Change it to

if #Players:GetPlayers() >= MinPlayers then

Where Players is the Players service

2 Likes