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

How do I choose 2 random players?

Sorry, but I'm in the process of creating a game. But, there's a problem: I have no idea how to choose 2 random players.

Any help?

3 answers

✓ Accepted answer

By using math.random of course!

while(true) do
	repeat wait() until game.Players.NumPlayers >=2
	 local Players=Game.Players:GetPlayers() 
 	local Chosen1, Chosen2 = math.random(1, #Players), 0
 	repeat Chosen2 = math.random(1, #Players) until Chosen2 ~= Chosen1
	print(Players[Chosen1].Name)
	print(Players[Chosen2].Name)
end

9 comments

0

Thanks so much! I'll get back to you if there are any errors.

0

The repeat wait() loop is really inefficient. You should be using this: while game.Players.NumPlayers < 2 do game.Players.PlayerAdded:wait() end

0

Hey Merely! Also, thanks.

0

@Thetacah, I changed the "print" to a Hint. But, it keeps saying it over and over again. Is that the repeat loop?

0

That would be the while true do loop, remove the Hint by doing this: Hint:Destroy() I put it in a while loop cause I thought you were making a round based game.

0

Oh, I see now.

0

How would I teleport the chosen players to a brick?

0

Very easy: Players[Chosen1].Character:MoveTo(Vector3.new(22.739, 13.5, -39.34)) Players[Chosen2].Character:MoveTo(Vector3.new(2.976, 14.372, -127.833))

0

Thanks so much! I'll leave you alone now. XD

Try :

local player = math.random(2, game.Players.NumPlayers);
local Players = game.Players:GetPlayers()

-- SCRIPT HERE --
-- Use player to actually apply to the two players.
-- Example :

player.Character:BreakJoints

Let's break it down.

To get a list of players, call game.Players:GetPlayers(). This returns a table of all the players in the game.

The table might look like this:

{
	[1] = game.Players.Merely;
	[2] = game.Players.MrSmenryBackup;
	[3] = game.Players.Test;
}

The first number you see is the index, which tells you what position in the table that element is at. For example, MrSmenryBackup's index is 2.

To select a random player from the table, you can use math.random. It gives you a random number between 1 and a number you pass in.

local players = game.Players:GetPlayers()
local randomPlayer = players[math.random(#players)]

If you put the pound sign (#) in front of a table, it gives you the number of entries in that table. So that code picks a random number between 1 and the number of players, and picks out the player from the table with that index.

2 comments

0

I don't want it to choose from a table, I want it to choose 2 players from the people in-game.

0

In Lua, a table is a list. For example, game.Workspace:GetChildren() returns a 'table' of objects.

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