Improving Teleport Code

Basically, I have made a script that automatically adds a new TextButton to a Frame depending on what is inside a Folder. Upon clicking the button it teleports you to that location. (hard to explain so hopefully these screenshots help)

GUI:
Screen Shot 2021-08-05 at 2.28.28 PM

Folder:
Screen Shot 2021-08-05 at 2.28.53 PM

E.g. clicking the “Home” button would teleport you to the “Home” part.

Code:

-- Client
for i,v in pairs(game.Workspace.LocationMarkers:GetChildren()) do
	local NewButton = script.Template:Clone()
	NewButton.Parent = script.Parent.Frame
	NewButton.Text = v.Name
	NewButton.Name = v.Name
end

for i,Button in pairs(script.Parent.Frame:GetChildren()) do
	if Button:IsA("TextButton") then
		Button.MouseButton1Click:Connect(function()
			for i,Part in pairs(game.Workspace.LocationMarkers:GetChildren()) do
				if Button.Name == Part.Name then
					game.ReplicatedStorage.TeleportSystem.TeleportPlayer:FireServer(Part.Position)
				end
			end
		end)
	end
end
-- Server
game.ReplicatedStorage.TeleportSystem.TeleportPlayer.OnServerEvent:Connect(function(player, location)
	player.Character.HumanoidRootPart.Position = location
end)

you should set the parent after you set the properties

NewButton.Text = v.Name
NewButton.Name = v.Name
NewButton.Parent = script.Parent.Frame
2 Likes

To teleport to locations use

Player.Character.HumanoidRooPart.CFrame = Location.CFrame

Adding on to @D0RYU, setting the parent property before setting the properties will make the script constantly look for the part and check if it still exists to set the properties but if you set the parent property after setting the properties, the script will already have the properties set and it’ll not have made the part yet so it doesn’t have to check for the part.

You can shorten the script to this:

script.Parent.MouseButton1Click:Connect(function()
local home = workspace.LocationMarkers.Home
local char = game.Players.LocalPlayer.Character or game.Players.LocalPlayer.CharacterAdded:Wait()
local root = char:WaitForChild("HumanoidRootPart")
root.CFrame = home.CFrame
end)

(Note: please put this in a local script inside the button)

1 Like