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

How do I make a script that selects 2 random players?

Asked by 4 years ago

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

0
Like I want to give each person a certain weapon Jade7070 0 — 4y
0
Try: game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())] ChristianTRPOC 64 — 4y

2 answers

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

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]

Ad
Log in to vote
0
Answered by
haba_nero 386 Moderation Voter
4 years ago
Edited 4 years ago
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.

Answer this question