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!
1 | local players = game.Players:GetChildren() |
2 |
3 | local selected = players [ math.random( 1 ,#players) ] |
You can use GetPlayers()
, which returns a table:
1 | local players = game.Players:GetPlayers() |
2 | 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.
01 | local playerNumber = 0 |
02 |
03 | for i, v in pairs (game.Players:GetChildren()) do |
04 | playerNumber = playerNumber + 1 |
05 | end |
06 |
07 | local selected = math.random( 1 , playerNumber) |
08 |
09 | for i, v in pairs (game.Players.GetChildren()) do |
10 | if i = = selected then |
11 | -- Change the team for v (v is the selected player) |
12 | end |
13 | end |