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 make a script that selects 2 random players?

So I've been trying to create a simple game, but need it to select 2 players to work.

2 comments

0

Like I want to give each person a certain weapon

0

Try: game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]

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.