Touch Part for random Part Teleport

i want when you touch a Part to teleport to other random parts, that’s what i tried but it doesn’t work

local Destination = workspace.TeleportDestination{"Teleport1", "Teleport2", "Teleport3", "Teleport4"}

script.Parent.Touched:Connect(function(Hit)
	local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
	if not Player then return end
	local Teleport = Destination[math.random(1, #Destination)]
	Player.Character:MoveTo(Teleport.Position)
end)

Can you tell me where I went wrong?

You cant call an Instance. You’re essentially doing this:

workspace.TeleportDestination({...})

You can use a pre-made array or use GetChildren instead.

local Destinations = {workspace.TeleportDestination.Teleport1} -- etc.
local Destinations = workspace.TeleportDestination:GetChildren()

-- teleport
local Teleport = Destinations[math.random(1, #Destinations)]

it still doesn’t work, but this is what the script looks like now

local Destinations = {workspace.TeleportDestination.Teleport1.Teleport2.Teleport3.teleport4} -- etc.
local Destinations = workspace.TeleportDestination:GetChildren()

script.Parent.Touched:Connect(function(Hit)
	local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
	if not Player then return end
	local Teleport = Destinations[math.random(1, #Destinations)]
	Player.Character:MoveTo(Teleport.Position)
end)

The Destinations is an or thing, you use one or the other. You also gotta learn to read the output, it should tell you that Teleport2 is not a valid member of Teleport1.

Remove the first line and use the second one instead.

now it seems that in the folder I can put as many parts as I want and it will work, correct?

Yes. It wont break assuming you are only adding parts in there.

Try this code, It should work the best.

script.Parent.Touched:Connect(function(Hit)
    local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
    if not Player then return end
    
    local TeleportDestinations = game.Workspace.TeleportDestination:GetChildren()
    
    if #TeleportDestinations > 0 then
        local RandomDestination = TeleportDestinations[math.random(#TeleportDestinations)]
        Player.Character:MoveTo(RandomDestination.Position)
    end
end)

I have a question, how can I teleport to just one without going through all of them at once?

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.