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

My script is not working, that detects how many players are in a game?

So I'm making a script to detect if 1 player is in the game, and it uses if statement.

p = game:GetService("Players"):GetChildren()
if p == 1 then
print ("One player.")
end

And it is not working, and it is in a script, not a local one, and I puted it in the Game.Players Pls tell me whats wrong if you can.

4 answers

✓ Accepted answer
p = game:GetService("Players"):GetChildren()
if #p == 1 then
print ("One player.")
end

You're welcome :) To get the length of the table (amount of players) you need to use # in front of it.

1 comment

0

Note that it's almost if not always a better idea to use :GetPlayers() instead of :GetChildren() when you want a list of players.

Hey Smach28,

There's another way to get the amount of players, that is way better than doing :GetChildren(). Also, :GetChildren() is about the worst way you can approach this because, what if there are other objects in the Players service? It will count those objects as players. I would recommend, if you're getting a table of Players, to do :GetPlayers() on the Players service, like this:

wait(2);
local player_service = game:GetService("Players")
local players = player_service:GetPlayers();
print(#players .. " is the amount of players.");

###That's one way to do it but, the way that I use most of the time is just to use the Players Service's NumPlayers property, to tell me the amount of players;

wait(2);
local players = game:GetService("Players");
local amount = players.NumPlayers;
print(amount .. " is the amount of players.");

##Well, I hope I helped and have a nice day/night.

~~ KingLoneCat

2 comments

0

Why would you add other things into the players service? That is the worst way to store things.

0

It's best to be safe with your scripts, than sorry. Which is why, it's best to use the most efficient methods you can in order to achieve what you need. You are just getting players so, for efficiency's sake :GetPlayers() is better than :GetChildren() just in-case you happen to put anything in the players service for whatever reason you might have.

Try this:

wait(1)
local p = game.Players:GetChildren()
print(#p.." Player(s)")

By adding the wait time, it waits for all the players to fully load in, and then it searches for all players, and lets you know how many players there are.

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