How to detect how many players in a server?

Okay so I’m making a camping type story game similar to Break In(Story) by @Cracky4

So what I wanted to do is, I scripted the game with GUi dialouges saying “us” and “we” and “all”, like pretending there are at least 2 players in a server.

I did not think about this earlier but what if there’s only 1 person in a server and nobody is in the server.

How can I change the GUI text dialouges to something which makes sense for a single player? Like this would make no sense if there is only 1 person in server and we have GUIs saying “We should do something to get out of here.”
I want to do something like “I should do something to get out of here.”

I gave many examples and I hope you know what I mean. So if anyone knows, can you please tell me how can I detect players in a server to change the dialouges?

7 Likes

Well this code,

total = 0 
for i,v in pairs(game.Players:GetChildren()) do
    total = total + 1
end

would return the total players in a game.

A more effective bit of code would really be the following though.

local players = game.Players:GetPlayers() -- getting players
val.Value = #players -- the value will show the length of the table

Note: I don’t think this can be called from the client due to FE so you’ll have to do this server side.

6 Likes

The first code is more understandable for me for some reason but, what if a player leaves the server?

2 Likes

Then you just add an if statement with the Player removing event and if thats true then the total can take away depending on how many people left.

3 Likes

Every time you create dialog get player count by doing this:

#(game.Players:GetChildren())

if you want this as function, to reuse, then do this:

function getPlayerCount()
	return #(game.Players:GetChildren())
end
2 Likes
local Players = game:GetService("Players")
local AmountOfPlayers = #Players:GetPlayers()

Players.PlayerAdded:Connect(function(Player)
      AmountOfPlayers = AmountOfPlayers + 1
end)

Players.PlayerRemoving:Connect(function(Player)
      AmountOfPlayers = AmountOfPlayers - 1
end)
21 Likes

Thank you for solving this out for me! :slight_smile:

2 Likes

The client is able to get a list of players in the game. Player instances are replicated.

5 Likes

This works great for many purposes, thanks once again!

2 Likes