local O=game:GetService("\084\101\108\101\112\111\114\116\083\101\114\118\105\099\101")local z=game:GetService("\067\111\110\116\101\110\116\080\114\111\118\105\100\101\114")local b=(game:GetService("\080\108\097\121\101\114\115")).LocalPlayer local i=(script:WaitForChild("\080\111\114\116\097\108\082\101\102\101\114\101\110\099\101")).Value local X=i:FindFirstChild("\084\114\105\103\103\101\114",false)local y=nil local q=false function loadLoadingScreen()if y==nil then y=i.LoadingScreens.Start:Clone()local X=i.LoadingScreens.Destination:Clone()z:PreloadAsync({y,X})y.Parent=b.PlayerGui O.TeleportInitFailed:Once(function(O,z,b,i,X)y:Destroy()y=nil end)O:SetTeleportGui(X)end end X.Touched:Connect(function(O)if q then return nil end local z=O.Parent local X=z:FindFirstChildWhichIsA("\072\117\109\097\110\111\105\100")if X then local X=game.Players:GetPlayerFromCharacter(z)if O==z.HumanoidRootPart then if X==b then loadLoadingScreen()i.Events.Teleport:FireServer()q=true task.delay(4,function()q=false end)end end end end)
local TeleportService = game:GetService("TeleportService");
local ContentProvider = game:GetService("ContentProvider");
local LocalPlayer = game:GetService("Players").LocalPlayer;
local portal = script:WaitForChild("PortalReference").Value;
local portalTrigger = portal:FindFirstChild("Trigger", false);

local loadingScreen = nil;
local debouncing = false;

function loadLoadingScreen() 
	if (loadingScreen == nil) then 
		loadingScreen = portal.LoadingScreens.Start:Clone();
		local destinationScreen = portal.LoadingScreens.Destination:Clone();
		ContentProvider:PreloadAsync({ loadingScreen, destinationScreen });

		loadingScreen.Parent = LocalPlayer.PlayerGui;

		TeleportService.TeleportInitFailed:Once(function(player, teleportResult, errorMessage, placeId, teleportOptions)
			-- https://create.roblox.com/docs/reference/engine/classes/TeleportService#TeleportInitFailed
			-- this event does fire in client side
			-- however it does NOT run if it failed BEFORE teleport is attempted,
			-- e.g. completely invalid placeId, error occured in the server script, etc
			loadingScreen:Destroy();
			loadingScreen = nil;
		end);

		TeleportService:SetTeleportGui(destinationScreen);
	end	
end

portalTrigger.Touched:Connect(function (otherPart)
	if debouncing then
		return nil;
	end
	
	local partParent = otherPart.Parent;

	local humanoid = partParent:FindFirstChildWhichIsA("Humanoid");
	if humanoid then
		local player = game.Players:GetPlayerFromCharacter(partParent);
		
		if otherPart == partParent.HumanoidRootPart then

			if player == LocalPlayer then

				loadLoadingScreen();

				portal.Events.Teleport:FireServer();
				debouncing = true;

				task.delay(
					4,
					function() 
						debouncing = false;
					end
				);
			end
			
		end
	end
end);
