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

How can I teleport random players onto different points of the map?

Say I do something like:

p= game.Players:GetChildren() 
for i= 1, #p do 

Can I do something like this to refer to a specified random player

p[1].Character.Torso.CFrame = CFrame.new(Vector3.new(blcks.Position.x,blcks.Position.y+3,blcks.Position.z))
p[2].Character.Torso.CFrame = CFrame.new(Vector3.new(blcks.Position.x,blcks.Position.y+3,blcks.Position.z))
p[3].Character.Torso.CFrame = CFrame.new(Vector3.new(blcks.Position.x,blcks.Position.y+3,blcks.Position.z))

Would it work that way?

1 answer

In a table, you can take the table's name followed by brackets and a number, and that gives you the value corresponding to the number. Thus, you can do something like this:

MyTable = {"Hi","There","Everyone"}
print(MyTable[1])

--*output: Hi*

Therefore, we can get a random value from a table by getting a random number, using math.random(). But what if the number is bigger than the amount of values in the table? That would mean that there would be no value corresponding to the number you gave! We don't want that. To fix this problem, you can do a number sign followed by the table's name. Doing this gives you the total amount of values in the table. So, if you get a random number between 1 and the number of values in the table, the random number will never be too big or too small.

MyTable = {"Hi","There","Everyone"}
print(MyTable[math.random(1, #MyTable)]

But this still does not give us a random player. Well, we can convert all the players in the server into a table, then use the same method as before.

Players = game.Players:GetPlayers()--This takes all the players in the server and converts that into a table.
print(Players[math.random(1, #Players)]

So now we've got a random player. But how do we move them around? There's 2 ways, actually. The first is to change the CFrame of the player's character model's torso.

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

randomPlayer.Character.Torso.CFrame = CFrame.new(x#,y#,z#)

The second way is to use the MoveTo() method on the character model itself.

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

randomPlayer.Character:MoveTo(Vector3.new(x#,y#,z#))

I hope I helped!

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