Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

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

Asked by
Smach28 10
6 years ago

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

Log in to vote
0
Answered by
Nowaha 459 Moderation Voter
6 years ago
Edited 6 years ago
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.

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. GoldenPhysics 474 — 6y
Ad
Log in to vote
1
Answered by 6 years ago

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

0
Why would you add other things into the players service? That is the worst way to store things. hiimgoodpack 2009 — 6y
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. KingLoneCat 2642 — 6y
Log in to vote
0
Answered by
Andorks 23
6 years ago

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.

Log in to vote
-1
Answered by
Smach28 10
6 years ago
p = game:GetService("Players"):GetChildren()

Answer this question