Player isn't being teleported back to their previous position after being teleported to another one

I’m trying to make a customization GUI where I have all the customization bits figured out for the most part. This is meant to teleport you to a room and then back to your position that you were at before you were customizing your character.

script.Parent.Activated:Connect(function()
	local plr = game.Players.LocalPlayer
	local chr = plr.Character or plr.CharacterAdded:Wait()
	local charpos = chr.HumanoidRootPart.CFrame
	script.Parent.Parent.Parent.Click:Play()
	script.Parent.Parent.Parent.Parent.Parent["In-game"].Hats.Enabled = not script.Parent.Parent.Parent.Parent.Parent["In-game"].Hats.Enabled
	if script.Parent.Parent.Parent.Parent.Parent["In-game"].Hats.Enabled then
		script.Parent.UIGradient.Rotation = -90
		local cam = workspace.CurrentCamera
		repeat wait()
		until
		cam.CameraSubject ~= nil
		cam.CameraType = Enum.CameraType.Scriptable
		cam.CFrame = workspace.campart.CFrame
		chr.HumanoidRootPart.CFrame = workspace.PosPart.CFrame
		chr.HumanoidRootPart.Anchored = true
	else
		chr.HumanoidRootPart.Anchored = false
		local cam = workspace.CurrentCamera
		cam.CameraType = Enum.CameraType.Custom
		script.Parent.UIGradient.Rotation = 90
		chr.HumanoidRootPart.CFrame = charpos
	end
end)

I’ve been browsing this site and another for how to teleport the player back to their position after they were teleported once but no solutions worked for me.

You are setting charpos inside of the event function, this means it gets set every time you run the script.

You can fix this by moving charpos outside of the script.Parent.Activated:Connect(function() end) and setting it inside the first condition of your if statement:

local charpos
script.Parent.Activated:Connect(function()
	local plr = game.Players.LocalPlayer
	local chr = plr.Character or plr.CharacterAdded:Wait()
	script.Parent.Parent.Parent.Click:Play()
	script.Parent.Parent.Parent.Parent.Parent["In-game"].Hats.Enabled = not script.Parent.Parent.Parent.Parent.Parent["In-game"].Hats.Enabled
	if script.Parent.Parent.Parent.Parent.Parent["In-game"].Hats.Enabled then
        charpos = chr.HumanoidRootPart.CFrame
		script.Parent.UIGradient.Rotation = -90
		local cam = workspace.CurrentCamera
		repeat wait()
		until
		cam.CameraSubject ~= nil
		cam.CameraType = Enum.CameraType.Scriptable
		cam.CFrame = workspace.campart.CFrame
		chr.HumanoidRootPart.CFrame = workspace.PosPart.CFrame
		chr.HumanoidRootPart.Anchored = true
	else
		chr.HumanoidRootPart.Anchored = false
		local cam = workspace.CurrentCamera
		cam.CameraType = Enum.CameraType.Custom
		script.Parent.UIGradient.Rotation = 90
		chr.HumanoidRootPart.CFrame = charpos
	end
end)
2 Likes