So I've been trying to create a simple game, but need it to select 2 players to work.
How do I make a script that selects 2 random players?
2 answers
First, you can use the :GetPlayers() method of the Players service, which will return a table containing all the current players.
Let's say you store it under a variable called 'plrs'.
You can then generate a random number, between 1 and the length of tbl 'plrs' like so: math.random(1, #plrs). The # symbol is what is used in lua to get the length of a table.
Let's say you store that under a variable called 'randomNum'.
You can then index the 'plrs' table with the random number you just generated, to give you a random item from the list. You can do this as many times as you like, and you can add them to a new table, or store them as variables.
I would recommend checking that the newly recieved random item doesn't already exist / hasn't been picked already.
You index it like this: local randomPlr = plrs[randomNum]
local Players = game.Players:GetPlayers
local ChosenPlayer1 = Players[math.random(1,#players)]
local ChosenPlayer2 = Players[math.random(1,#players)]
local Different = false
while Different == false do
if ChosenPlayer1.Name == ChosenPlayer2.Name then
ChosenPlayer2 = Players[math.random(1,#players)]
else
Different = true
--Your code here. Use ChosenPlayers as variables
end
wait()
end
This should work fine. It picks two different players.
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
Like I want to give each person a certain weapon
Try: game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]