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

Is there a simply way to return two random players?

`function ChooseRandomPlayer()
	local GamePlayers = game.Players:GetChildren()

	local ChosenPlayer = GamePlayers[math.random(1, #GamePlayers)] -- The "#" just means the number of things inside that model.
	if ChosenPlayer then
		local player1 = ChosenPlayer
		local ChosenPlayer2 = GamePlayers[math.random(1, #GamePlayers)]
		if player1 == ChosenPlayer2 then
			local ChosenPlayer3 = GamePlayers[math.random(1, #GamePlayers)]
			if player1 == ChosenPlayer3 then
				local ChosenPlayer4 = GamePlayers[math.random(1, #GamePlayers)]
				if player1 == ChosenPlayer4 then
					local ChosenPlayer5 = 		GamePlayers[math.random( > 1,#GamePlayers)]
					return ChosenPlayer5,ChosenPlayer --
				else 
					return ChosenPlayer4,ChosenPlayer
				end
			else 
				return ChosenPlayer3,ChosenPlayer
			end
		else 
			return ChosenPlayer2,ChosenPlayer
		end

	end
end`

At the moment I have the script..

  • Find one random player and then find another
  • Check to see if it is the same player
  • If it is the same player, then check again. If it isn't, return the two players and end.
  • This cycle repeats 4 more times, considering it is unlikely to find the same player 6 total times...

I feel as if I am being silly in my methods of doing this. Surely there is another, simpler way to find two different random players?

1 answer

✓ Accepted answer

You could use a loop to keep on generating a new random player until the two players selected are different.

function ChooseRandomPlayer()
	local GamePlayers = game.Players:GetChildren()
	if #GamePlayers > 1 then
		local player1
		local player2
		repeat
			player1 = GamePlayers[math.random(1 , #GamePlayers)]
			player2 = GamePlayers[math.random(1 , #GamePlayers)]
		until player1 ~= player2
		return player1 , player2
	end
end

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