Check how many players are in the game

Hello! I have a script where it checks how many players. Though its not working? I want it so the game starts when there is 2 players

LocalScript:

local Debouce = false

while wait(0.1) do
	if game.Players:GetPlayers() == 1 then
		GameText.Text = "2 Players are needed to continue."
		print("2 Players Needed")
		Debouce = false
	else
		if Debouce == false then
			Debouce = true
			game.ReplicatedStorage.GameStart:FireServer()
			print("Game Starting")
		end
	end
end

You should be checking how many players are in the game on the server side (I assume this is the client based on GameStart:FireServer()

local GameStarted = false

function StartGame()
  if GameStarted then return end

  GameStarted = true

  --Game Code
end

while wait(0.1) and not GameStarted do
  if #game:GetService("Players"):GetPlayers() >= 2 then --The # at the start checks the count. Then we can just check if there are 2 or more players
    StartGame()
  else
    print("Waiting for enough players to start.")
  end
end

And if you need a GUI to show text saying that it’s waiting for players to start, you can always just:

  1. Use GetAttribute() & SetAttribute() (I would do this on Players or ReplicatedStorage. Set it on the Server, Get is on the Client.)
  2. Use a BoolValue in ReplicatedStorage
  3. Use a RemoteEvent and :FireAllClients(“Waiting for enough players!”)
1 Like