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

How Do I get all the Players and Pick A Random One?

Asked by 5 years ago

Hello, I've been trying to get a random player from the game and then change their team. I'm pretty sure how to do the team change but not picking a random player, the only thing I've really done was something to get every player which was fairly easy but otherwise I'm clueless. If you can help me, thank you!

3 answers

Log in to vote
1
Answered by
SurfedZ 36
5 years ago
Edited 5 years ago
local players = game.Players:GetChildren()

local selected = players[math.random(1,#players)]
0
That does not work either. You get the same error. DeceptiveCaster 3761 — 5y
0
ill check SurfedZ 36 — 5y
0
i changed it and worked, but you cant just put it at serverscriptservice without a interval, because needs to wait atleast a player join SurfedZ 36 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

You can use GetPlayers(), which returns a table:

local players = game.Players:GetPlayers()
print(players[math.random(1, #players)]) -- Prints a random player

The reason why the other two solutions don't work is because you're attempting to use a Service (which is Players) as a table. Services are not tables and they should not be used like tables.

0
Thanks! MarioGenci -5 — 5y
Log in to vote
0
Answered by 5 years ago
local playerNumber = 0

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

local selected = math.random(1, playerNumber)

for i, v in pairs(game.Players.GetChildren()) do
    if i == selected then
        -- Change the team for v (v is the selected player)
    end
end
0
GetPlayers() please... DeceptiveCaster 3761 — 5y

Answer this question