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

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

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

local players = game.Players:GetChildren()

local selected = players[math.random(1,#players)]

3 comments

0

That does not work either. You get the same error.

0

ill check

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

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.

1 comment

0

Thanks!

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

1 comment

0

GetPlayers() please...

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