How to get the current number of players?

So I am making a script that wont let the match run if there are not 4 players in game. So what happens is that it runs but will not activate when there are 4 players

while true do
print("starting")
if #amountOfPlayers >= 4 then
	print("ready")
	ready = true
end
print("1")
	wait(2.5)
	if #amountOfPlayers <= 3 then -- fix
	ready = false
	end
	print("boopz")
	if 	ready == false then
		
	end
	
	if ready then
		print("starting intermission")
		wait("15")
		print("starting match")
		assignRoles(mafia)
		print(mafia.." is the mafia.")
		wait(180)
	end
 wait(5)
end

I recommend restructuring your game loop to something like this, where mafia and assignRoles() have been defined by you somewhere above:

local MIN_PLAYERS = 4
local ROUND_TIME = 180
local INTERMISSION_TIME = 15

local Players = game:GetService("Players")
-- local mafia = nil (you'll need to define this)

--[[
local function assignRoles(mafia)
	-- your function here
end
]]

while true do
	while #Players:GetPlayers() < MIN_PLAYERS do
		print("Waiting for 4 players...")
		wait(1)
	end
	
	-- Your game round logic here
	print("Starting round!")
	assignRoles(mafia)
	print(mafia .. " is the mafia.")
	wait(ROUND_TIME)
	print("Round over! Intermission...")
	
	wait(INTERMISSION_TIME)
end
1 Like

you could do it like this:

while true do
    repeat wait() until #amountOfPlayers > 3
    - run code
end

Edit: actually what he has above is a lot better :smiley:

1 Like

Thanks for the response, I will try this.

I just get Waiting for 4 players forever.

Just to cover the bases here, you are testing with 4 or more players?

Yes, using a local server. In the studio

Wait got it too work. I forgot to put a # lol.