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

How would I go about making a World Script that selects 2 players at random?

I'm making a game that requires two individual players to be selected from the server. I'm having trouble because my script sometimes selects the same player twice! Please help here is my code:

math.randomseed(tick())

local randomPlayer1 = game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]

randomPlayer1.Character.HumanoidRootPart.CFrame = CFrame.new(Vector3.new(9.325, 5.81, 7.645))

--Set Player to not move
wait(0.000001)
randomPlayer1.Character.Humanoid.WalkSpeed = 0
randomPlayer1.Character.Humanoid.JumpPower = 0
wait(0.000001)--Double Safe
randomPlayer1.Character.Humanoid.WalkSpeed = 0
randomPlayer1.Character.Humanoid.JumpPower = 0

--Need to set orientation

randomPlayer1.Character.HumanoidRootPart.Orientation = Vector3.new(0, 0, 0)

serV.Text = "New Player, " .. randomPlayer1.Name .. ". Has been Selected!"

Output1.Text = "Opponent 1: " .. randomPlayer1.Name

wait(3)
	
serV.Text = "Searching for Opponents!"
	
wait(3)

math.randomseed(tick())

local randomPlayer2 = game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]

serV.Text = "New Player, " .. randomPlayer2.Name .. ". Has been Selected!"

Output2.Text = "Opponent 2: " .. randomPlayer2.Name
		
randomPlayer2.Character.HumanoidRootPart.CFrame = CFrame.new(Vector3.new(9.325, 5.81, -6.787))

--Set Player to not move
wait(0.000001)
randomPlayer1.Character.Humanoid.WalkSpeed = 0
randomPlayer1.Character.Humanoid.JumpPower = 0
wait(0.000001) --Double Safety
randomPlayer1.Character.Humanoid.WalkSpeed = 0
randomPlayer1.Character.Humanoid.JumpPower = 0


--Need to set orientation

randomPlayer2.Character.HumanoidRootPart.Orientation = Vector3.new(0, 180, 0)
		
wait(2)
		
serV.Text = "Round Beggining!"

1 answer

✓ Accepted answer

There are a lot of ways to do this, I'll explain a couple.

Repeat loop

What you can do is store Player1 picked and when the server picks the next person, it'll keep picking people until the picked player isn't Player1.

local Players = game.Players:GetPlayers()

local Player1 = Players[math.random(1, #Players)]
local Player2

repeat
	Player2 = Players[math.random(1, #Players)]
until (Player2 ~= Player1)

Table

Make a table of the players and once you pick Player1, remove him/her from the table that way you don't pick the same person again.

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