Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to count players ingame to check if the game should start?

while true do
	
	Status.Value = "Waiting for enough players"
	
	game.Players:GetPlayers()
	repeat wait(1) until Players >= 2
	
	Status.Value = "Intermission"

I know this is very wrong but this is deprecated

repeat wait() until game.Players.NumPlayers >= 2

2 comments

0

simple use: repeat wait(1) until #game.Players:GetPlayers() >= 2

0

ew no

4 answers

✓ Accepted answer

In adaptation to yHasteeD's recommendation of: "you can simple use: repeat wait() until #game.Players:GetPlayers() >= 2"

Since that'd just run once and not account for a potential player drop (players leaving)

You could do:

local players = game.Players

function playerAdded()
	local plramount = #players:GetPlayers()
	if plramount>=2 then
		game()
	end
end
players.PlayerAdded:connect(playerAdded)

function game()
	-- game stuff here, make all functions in game end if #players:GetPlayers() < 2
end

The function you're looking for is a function of Players called GetPlayers https://developer.roblox.com/api-reference/function/Players/GetPlayers

repeat wait() until game.Players:GetPlayers() >= 2

5 comments

0

Functions return values. The sentinel value of GetPlayers is the amount of players that are in the game. With that data, we can compare it.

1

#, your script will error

1

GetPlayers() returns a table of player instances, the number of players would be equal to the length of this table so the length operator '#' should be prepended to this table

0

My bad. Don't know why I thought GetPlayers returned an integer. Exactly what Gold said.

0

Edit your answer to repeat wait() until #game.Players:GetPlayers() >= 2

local Players = game:GetService("Players")
local PlayerCount = 0

game.Players.PlayerAdded:Connect(function()
	PlayerCount = PlayerCount + 1
end)

game.Players.PlayerRemoving:Connect(function()
	PlayerCount = PlayerCount - 1
end)

while PlayerCount < 1 do
	repeat wait(1) until PlayerCount >= 2
end

1 comment

0

You can simple use repeat wait(1) until #Players:GetPlayers() >= 2

There are many ways of doing this but I just went with my method. Accept if this helped :)

local players = {}

function get_players()
	players = {}

	for _, a in pairs(game:service'Players':players'') do --// gets all players
		table.insert(players, a) --// inserts all player to the table 
	end

	return #players --// returns the count of players
end

repeat wait() until get_players() >= 2

1 comment

0

you can simple use: repeat wait() until #game.Players:GetPlayers() >= 2

This discussion is preserved as it was. New answers, comments, and votes are closed.