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

How do I check how many players are in a game before starting a function?

Hello, I have an intermission system in my game, and I'm trying to make it so you need 2 players for a game to start. The intermission works before I added this, and now the status wont change. The thing I made to check if there are two players is at the bottom of the script, everything else I left in just n case it has something to do with it.

local IntermissionLength = 10
local RoundLength = 10

local InRound = game.ReplicatedStorage.InRound
local Status = game.ReplicatedStorage.Status

local HomePlatform = game.Workspace.HomePlatform
local TilePlatform = game.Workspace.TilePlatform


InRound.Changed:Connect(function()
	print(InRound.Value)
	if InRound.Value == true then
		for _, player in pairs(game.Players:GetChildren()) do
			local char = player.Character
			char.HumanoidRootPart.CFrame = TilePlatform.CFrame
		end
		
	elseif InRound.Value == false then
		for _, player in pairs(game.Players:GetChildren()) do
			local char = player.Character
			char.HumanoidRootPart.CFrame = HomePlatform.CFrame
		end
	end
end)

--The timer function
local function Timer()
	while wait() do
		for i = IntermissionLength, 0, -1 do
			InRound.Value = false
			wait(1)
			Status.Value = "Intermission for "..i.." more seconds!"
		end
		
		for i = RoundLength, 0,-1 do
			InRound.Value = true
			wait(1)
			Status.Value = "Game going on for "..i.." more seconds!"
		end
	end
end

--Newest part of the code starts here
local plrcount = 0

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

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

if plrcount >= 2 then
	--Activates the timer (worked already)
	spawn(Timer)
elseif plrcount == 1 then
	Status.Value = "Not enough players for the game to start"
	print(Status.Value)
	while wait(5) do
		if plrcount >= 2 then
			spawn(Timer)
		end
	end
end

1 answer

You can use something like this

game.Players:GetPlayers()

That returns an array of the players instances, so you can just do

local PlayersList = game.Players:GetPlayers()
print(#PlayersList )

Also if you want to iterate it, you can just do

for _, player in ipairs(PlayersList) do
	print(player.Name)
end

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