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

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

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

✓ Accepted answer

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.

8 comments

0

Thank you, so after I pick the 2nd player, would I just do table.insert(plrs, n)?

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!

0

But how do I insert the player back in the table? It's not a function, and I'm not waiting.

0

@ChillTart You don't need/want to do that. Forget about the table it no longer servers a purpose for you.

0

So I would just create a new table? I still want to do stuff to the players in the table.

0

@DanzLua

0

@ChillTart Yes, just set players=game.Players:GetPlayers() and acquire a fresh new table.

0

Alright, thank you. Very helpful. @DanzLua

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