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

So I want to select 2 random players, how do I do it?

Asked by 5 years ago
Edited by DanzLua 5 years ago
local chosenPlayer = plrs[math.random(1, #plrs)]
local chosenPlayer2 = plrs[math.random(1, #plrs]
--[[ The possibility is that the same player could be selected twice, how do I make sure that it doesn't do that?]]

1 answer

Log in to vote
0
Answered by
DanzLua 2879 Moderation Voter Community Moderator
5 years ago

First we need to get a table of current players using

local players=game.Players:GetPlayers()

Then we can use math.random() to choose a player, using players[i] and then remove that player from the table using its index so that we can't choose it again.

local players=game.Players:GetPlayers()

local n=math.random(1,#players)
local player1=players[n]
table.remove(players,n)

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

I use the variable n so that I can choose a player and remove with since that is the index.

0
Thank you, so after I pick the 2nd player, would I just do table.insert(plrs, n)? ChillTart 4 — 5y
0
@ChillTart No, if you were waiting or if this is in a function, you want to get a fresh new list of current players. Also accept the answer if it helps! DanzLua 2879 — 5y
0
But how do I insert the player back in the table? It's not a function, and I'm not waiting. ChillTart 4 — 5y
0
@ChillTart You don't need/want to do that. Forget about the table it no longer servers a purpose for you. DanzLua 2879 — 5y
View all comments (4 more)
0
So I would just create a new table? I still want to do stuff to the players in the table. ChillTart 4 — 5y
0
@DanzLua ChillTart 4 — 5y
0
@ChillTart Yes, just set players=game.Players:GetPlayers() and acquire a fresh new table. DanzLua 2879 — 5y
0
Alright, thank you. Very helpful. @DanzLua ChillTart 4 — 5y
Ad

Answer this question