Need Help on Teleporting the player to a Random Part

I want to make a game where when the player clicks a button they are teleported to a Dark Room and then after about a second, they are then teleported to a random room.

The issue I have here is I am not sure how to teleport the player in If statements but I have made this script here.

I am quite new to creating games so the solutions to this problem that I searched up were pretty confusing to me.

Any help is appreciated and thank you :smiley:

2 Likes

if you just want to teleport the player, add a player variable inside of the function like this:

script.Parent.ClickDetector.MouseClick:Connect(function(player)

then, you can do this:

player.Character.HumanoidRootPart.CFrame = CFrame.new(game.Workspace.Part.Position)--replace part with the name of the part, or replace the location to the location of the part.
1 Like

It works :smiley:
Thanks so much!

This can be made a million times more efficient and easy to understand using tables!

I made up some code for you and commented how to use it.
It’s worth noting that both samples of code will work perfectly fine and you can use whichever you prefer.

local Parts = {
    workspace.Part1,
    workspace.Part2,
    workspace.Part3
} -- Reference all of your parts in a condensed table. More on this later.

script.Parent.ClickDetector.MouseClick:Connect(function(Player)
    local Character = Player.Character or nil -- Find the player's character, or simply do not define a character (to prevent errors if the player is dead)

    if not Character then return end -- If the character does not exist, escape all possibilities of errors by ending the function
    local HRP = Character:FindFirstChild("HumanoidRootPart") -- We will be using this a lot later, so it's best to shorten it down

    HRP.CFrame = workspace.FirstPart.CFrame -- Reference the part you wanted the player to teleport to first
    wait(1) -- speaks for itself

    local n = math.random(1, #Parts) -- Create a random number from 1 (the lowest index in any Lua table) to the length of parts (#Parts)

    HRP.CFrame = Parts[n].CFrame -- Teleport the player to the CFrame of the selected part, specified by the number which was randomly generated before
end)

Hope this helps!

Happy coding.

6 Likes