Okay, let's add a GUI countdown to the teleport system. This will involve creating a GUI, a RemoteEvent for server-client communication, and a LocalScript to manage the GUI on the client.
Step 1: Set up the GUI in Roblox Studio
In the Explorer window, right-click on StarterGui.
Hover over Insert Object and click on ScreenGui. Name it TeleportCountdownGui.
Inside TeleportCountdownGui, right-click and insert a TextLabel. Name it CountdownLabel.
Configure CountdownLabel's properties:
Text: "Teleporting in..." (or anything you like)
BackgroundTransparency: 1 (makes it invisible)
Size: UDim2.new(0.3, 0, 0.1, 0) (adjust as needed)
Position: UDim2.new(0.5, 0, 0.1, 0) (top center of the screen)
AnchorPoint: 0.5, 0 (important for centering)
TextColor3: Color3.fromRGB(255, 255, 255) (white)
TextScaled: true (text will automatically resize to fit)
TextStrokeTransparency: 0 (adds a black outline for readability)
Font: SourceSansBold (or any other bold font)
Visible: false (this will be controlled by the script)
Configure TeleportCountdownGui's properties:
Enabled: false (this will be controlled by the script)
ResetOnSpawn: true (default, ensures it resets when player respawns)
Step 2: Create a RemoteEvent
In the Explorer window, right-click on ReplicatedStorage.
Hover over Insert Object and click on RemoteEvent. Name it TeleportCountdownEvent.
Step 3: Modify the Server Script
This script will tell the client when to start and stop the countdown.
Location:ServerScriptService (the same script you used before)
lua
Step 4: Create the LocalScript for the GUI
This script will run on the player's computer and update the GUI.
Location: Inside TeleportCountdownGui (the ScreenGui you created).
RemoteEvent in ReplicatedStorage: TeleportCountdownEvent
Verify Script Placement:
Main teleport script: ServerScriptService
GUI script: Inside TeleportCountdownGui
Double-check the TARGET_PLACE_ID.
Publish your game and test it by playing it on Roblox (not just in Studio's "Play Solo" for teleport functions).
Now, when a player stands on the "teleport" part, they will see a countdown display, and if they step off, the countdown will disappear.
User
make the gui automatically just by using scripts, no need for screengui
Assistant
You got it! We can create the ScreenGui and TextLabel entirely through a LocalScript.
This involves:
Removing the pre-made ScreenGui and TextLabel from StarterGui.
Keeping the RemoteEvent in ReplicatedStorage as it's the bridge between server and client.
Updating the LocalScript to create these GUI elements on the fly.
The Server Script remains the same, as it only interacts with the RemoteEvent.
Step 1: Clean up your Studio
DeleteTeleportCountdownGui (and its child CountdownLabel) from StarterGui.
Ensure you still have the RemoteEvent named TeleportCountdownEvent in ReplicatedStorage.
Step 2: The Server Script (No Changes)
This script remains exactly the same as in the previous solution.
Location:ServerScriptService
lua
--!nolint LocalShadow
-- Services
local Players = game:GetService("Players")
local TeleportService = game:GetService("TeleportService")
local Workspace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage") -- New: Service for RemoteEvent
-- Configuration
local TELEPORT_PART_NAME = "teleport"
local TARGET_PLACE_ID = 103427078304728 -- <<< CHECK THIS ID CAREFULLY!
local TELEPORT_DELAY = 5 -- Seconds to wait before teleporting
-- Remote Events
-- This is how the server communicates with the player's GUI
local TeleportCountdownEvent = ReplicatedStorage:FindFirstChild("TeleportCountdownEvent")
if not TeleportCountdownEvent or not TeleportCountdownEvent:IsA("RemoteEvent") then
warn("TeleportCountdownEvent not found in ReplicatedStorage or is not a RemoteEvent.")
warn("GUI countdown will NOT function. Please ensure it's named 'TeleportCountdownEvent' in ReplicatedStorage.")
-- Optional: You might want to halt the script if this is critical, but we'll let the teleport still work.
end
-- Find the teleport part
local teleportPart = Workspace:FindFirstChild(TELEPORT_PART_NAME, true)
-- Table to keep track of players currently on the part and their countdown threads
local playersOnPart = {}
-- Function to handle teleportation
local function attemptTeleport(player)
if not player then return end
print("Attempting to teleport player:", player.Name, "to Place ID:", TARGET_PLACE_ID)
local success, result = pcall(function()
TeleportService:TeleportAsync(TARGET_PLACE_ID, {player})
end)
if not success then
warn("Teleport failed for player:", player.Name, "- Error:", tostring(result))
else
print("Teleport initiated for player:", player.Name)
end
end
-- Function to start the countdown
local function startCountdown(player)
if playersOnPart[player] then
return -- Countdown already running for this player
end
print(player.Name, "stepped on the teleport pad. Starting "..TELEPORT_DELAY.."-second countdown.")
-- Tell the client to start their GUI countdown
if TeleportCountdownEvent then
TeleportCountdownEvent:FireClient(player, "start", TELEPORT_DELAY)
end
local countdownThread = task.spawn(function()
task.wait(TELEPORT_DELAY)
-- IMPORTANT: Check if the player is *still* supposed to be teleporting.
-- If playersOnPart[player] is nil, it means they left the part and
-- the thread was (or should have been) cancelled or cleared.
if playersOnPart[player] == coroutine.running() then
playersOnPart[player] = nil -- Clear their entry before teleporting
attemptTeleport(player)
end
end)
playersOnPart[player] = countdownThread
end
-- Function to stop the countdown
local function stopCountdown(player)
local thread = playersOnPart[player]
if thread then
print(player.Name, "left the teleport pad. Cancelling countdown.")
task.cancel(thread) -- Cancel the waiting thread
playersOnPart[player] = nil -- Remove them from the tracking table
-- Tell the client to stop their GUI countdown
if TeleportCountdownEvent then
TeleportCountdownEvent:FireClient(player, "stop")
end
end
end
-- Function to handle when something touches the part
local function onPartTouched(otherPart)
local character = otherPart.Parent
if not character then return end
local humanoid = character:FindFirstChildOfClass("Humanoid")
if not humanoid or humanoid.Health <= 0 then return end
local player = Players:GetPlayerFromCharacter(character)
if player then
startCountdown(player)
end
end
-- Function to handle when something stops touching the part
local function onPartTouchEnded(otherPart)
local character = otherPart.Parent
if not character then return end
local player = Players:GetPlayerFromCharacter(character)
if player then
stopCountdown(player)
end
end
-- Function to handle players leaving the game
local function onPlayerRemoving(player)
-- If the player was on the pad when they left, clean up
stopCountdown(player)
end
-- Main Setup
if teleportPart and teleportPart:IsA("BasePart") then
print("Teleport part '"..TELEPORT_PART_NAME.."' found. Setting up connections.")
teleportPart.Touched:Connect(onPartTouched)
teleportPart.TouchEnded:Connect(onPartTouchEnded)
Players.PlayerRemoving:Connect(onPlayerRemoving)
teleportPart.Anchored = true
teleportPart.CanCollide = false
teleportPart.CanTouch = true
else
warn("Teleport part named '"..TELEPORT_PART_NAME.."' was not found in Workspace!")
warn("The teleport script will NOT function.")
end
--!nolint LocalShadow
-- Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService") -- Used for updating GUI smoothly
-- Get GUI elements
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
local teleportCountdownGui = playerGui:WaitForChild("TeleportCountdownGui")
local countdownLabel = teleportCountdownGui:WaitForChild("CountdownLabel")
-- Get Remote Event
local TeleportCountdownEvent = ReplicatedStorage:FindFirstChild("TeleportCountdownEvent")
if not TeleportCountdownEvent or not TeleportCountdownEvent:IsA("RemoteEvent") then
warn("TeleportCountdownEvent not found in ReplicatedStorage or is not a RemoteEvent. GUI will not function.")
script:Destroy() -- Destroy this script if essential components are missing
end
-- State variables for the countdown
local activeCountdownThread = nil
local countdownStartTime = 0
local totalCountdownDuration = 0
-- Function to update the GUI display
local function updateCountdownDisplay()
-- Calculate remaining time. math.max(0, ...) ensures it doesn't go negative.
-- math.ceil rounds up to the nearest whole second.
local remainingTime = math.max(0, totalCountdownDuration - (os.time() - countdownStartTime))
countdownLabel.Text = "Teleporting in: " .. math.ceil(remainingTime) .. "..."
end
-- Function to start the client-side countdown
local function startClientCountdown(duration)
-- If a countdown is already running, stop it first to prevent multiple threads
if activeCountdownThread then
task.cancel(activeCountdownThread)
activeCountdownThread = nil -- Clear reference
end
totalCountdownDuration = duration
countdownStartTime = os.time() -- Record the precise start time
teleportCountdownGui.Enabled = true -- Make the ScreenGui visible
countdownLabel.Visible = true -- Make the TextLabel visible
-- Start a new thread to update the countdown every frame
activeCountdownThread = task.spawn(function()
while RunService.RenderStepped:Wait() do -- 'RenderStepped' fires just before the frame renders
updateCountdownDisplay()
if os.time() - countdownStartTime >= totalCountdownDuration then
break -- Countdown finished
end
end
-- After the loop finishes (countdown completed or stopped)
task.wait(0.1) -- Give a tiny moment for the last number to show before hiding
teleportCountdownGui.Enabled = false
countdownLabel.Visible = false
activeCountdownThread = nil -- Clear the thread reference
end)
end
-- Function to stop the client-side countdown
local function stopClientCountdown()
if activeCountdownThread then
task.cancel(activeCountdownThread) -- Cancel the running countdown thread
activeCountdownThread = nil
end
teleportCountdownGui.Enabled = false -- Hide the ScreenGui
countdownLabel.Visible = false -- Hide the TextLabel
end
-- Listen for the RemoteEvent from the server
TeleportCountdownEvent.OnClientEvent:Connect(function(action, data)
if action == "start" then
startClientCountdown(data) -- data will be the TELEPORT_DELAY value
elseif action == "stop" then
stopClientCountdown()
end
end)
-- Initial state: Hide the GUI when the game starts
teleportCountdownGui.Enabled = false
countdownLabel.Visible = false
--!nolint LocalShadow
-- Services
local Players = game:GetService("Players")
local TeleportService = game:GetService("TeleportService")
local Workspace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- Configuration
local TELEPORT_PART_NAME = "teleport"
local TARGET_PLACE_ID = 103427078304728 -- <<< CHECK THIS ID CAREFULLY!
local TELEPORT_DELAY = 5 -- Seconds to wait before teleporting
-- Remote Events
local TeleportCountdownEvent = ReplicatedStorage:FindFirstChild("TeleportCountdownEvent")
if not TeleportCountdownEvent or not TeleportCountdownEvent:IsA("RemoteEvent") then
warn("TeleportCountdownEvent not found in ReplicatedStorage or is not a RemoteEvent.")
warn("GUI countdown will NOT function. Please ensure it's named 'TeleportCountdownEvent' in ReplicatedStorage.")
end
-- Find the teleport part
local teleportPart = Workspace:FindFirstChild(TELEPORT_PART_NAME, true)
-- Table to keep track of players currently on the part and their countdown threads
local playersOnPart = {}
-- Function to handle teleportation
local function attemptTeleport(player)
if not player then return end
print("Attempting to teleport player:", player.Name, "to Place ID:", TARGET_PLACE_ID)
local success, result = pcall(function()
TeleportService:TeleportAsync(TARGET_PLACE_ID, {player})
end)
if not success then
warn("Teleport failed for player:", player.Name, "- Error:", tostring(result))
else
print("Teleport initiated for player:", player.Name)
end
end
-- Function to start the countdown
local function startCountdown(player)
if playersOnPart[player] then
return
end
print(player.Name, "stepped on the teleport pad. Starting "..TELEPORT_DELAY.."-second countdown.")
if TeleportCountdownEvent then
TeleportCountdownEvent:FireClient(player, "start", TELEPORT_DELAY)
end
local countdownThread = task.spawn(function()
task.wait(TELEPORT_DELAY)
if playersOnPart[player] == coroutine.running() then
playersOnPart[player] = nil
attemptTeleport(player)
end
end)
playersOnPart[player] = countdownThread
end
-- Function to stop the countdown
local function stopCountdown(player)
local thread = playersOnPart[player]
if thread then
print(player.Name, "left the teleport pad. Cancelling countdown.")
task.cancel(thread)
playersOnPart[player] = nil
if TeleportCountdownEvent then
TeleportCountdownEvent:FireClient(player, "stop")
end
end
end
-- Function to handle when something touches the part
local function onPartTouched(otherPart)
local character = otherPart.Parent
if not character then return end
local humanoid = character:FindFirstChildOfClass("Humanoid")
if not humanoid or humanoid.Health <= 0 then return end
local player = Players:GetPlayerFromCharacter(character)
if player then
startCountdown(player)
end
end
-- Function to handle when something stops touching the part
local function onPartTouchEnded(otherPart)
local character = otherPart.Parent
if not character then return end
local player = Players:GetPlayerFromCharacter(character)
if player then
stopCountdown(player)
end
end
-- Function to handle players leaving the game
local function onPlayerRemoving(player)
stopCountdown(player)
end
-- Main Setup
if teleportPart and teleportPart:IsA("BasePart") then
print("Teleport part '"..TELEPORT_PART_NAME.."' found. Setting up connections.")
teleportPart.Touched:Connect(onPartTouched)
teleportPart.TouchEnded:Connect(onPartTouchEnded)
Players.PlayerRemoving:Connect(onPlayerRemoving)
teleportPart.Anchored = true
teleportPart.CanCollide = false
teleportPart.CanTouch = true
else
warn("Teleport part named '"..TELEPORT_PART_NAME.."' was not found in Workspace!")
warn("The teleport script will NOT function.")
end
Step 3: The LocalScript (Creates GUI programmatically)
This script will now create the ScreenGui and TextLabel when the player joins the game.
Location: You can place this LocalScript directly under StarterPlayer.StarterPlayerScripts or StarterGui (it will be copied to PlayerGui when the player loads). Placing it in StarterGui makes sense as it's a GUI-related script.
To place it:
Right-click on StarterGui.
Hover over Insert Object and click LocalScript.
Name it TeleportCountdownClient.
Paste the code below:
lua
--!nolint LocalShadow
-- Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
-- Get player and PlayerGui
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
-- Get Remote Event
local TeleportCountdownEvent = ReplicatedStorage:FindFirstChild("TeleportCountdownEvent")
if not TeleportCountdownEvent or not TeleportCountdownEvent:IsA("RemoteEvent") then
warn("TeleportCountdownEvent not found in ReplicatedStorage or is not a RemoteEvent. GUI will not function.")
script:Destroy() -- Self-destruct if essential components are missing
end
-- State variables for the countdown
local activeCountdownThread = nil
local countdownStartTime = 0
local totalCountdownDuration = 0
-- Function to create and configure the GUI
local teleportCountdownGui
local countdownLabel
local function setupGui()
teleportCountdownGui = Instance.new("ScreenGui")
teleportCountdownGui.Name = "TeleportCountdownGui"
teleportCountdownGui.ResetOnSpawn = true -- Important: Ensures GUI reappears/resets on player respawn
teleportCountdownGui.Enabled = false -- Start hidden
teleportCountdownGui.Parent = playerGui
countdownLabel = Instance.new("TextLabel")
countdownLabel.Name = "CountdownLabel"
countdownLabel.Text = "Teleporting in..."
countdownLabel.BackgroundTransparency = 1
countdownLabel.Size = UDim2.new(0.3, 0, 0.1, 0)
countdownLabel.Position = UDim2.new(0.5, 0, 0.1, 0)
countdownLabel.AnchorPoint = Vector2.new(0.5, 0) -- Center horizontally from its position
countdownLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
countdownLabel.TextScaled = true
countdownLabel.TextStrokeTransparency = 0
countdownLabel.Font = Enum.Font.SourceSansBold
countdownLabel.Visible = false -- Start hidden
countdownLabel.Parent = teleportCountdownGui
end
-- Function to update the GUI display
local function updateCountdownDisplay()
local remainingTime = math.max(0, totalCountdownDuration - (os.time() - countdownStartTime))
countdownLabel.Text = "Teleporting in: " .. math.ceil(remainingTime) .. "..."
end
-- Function to start the client-side countdown
local function startClientCountdown(duration)
if activeCountdownThread then
task.cancel(activeCountdownThread)
activeCountdownThread = nil
end
totalCountdownDuration = duration
countdownStartTime = os.time()
teleportCountdownGui.Enabled = true
countdownLabel.Visible = true
activeCountdownThread = task.spawn(function()
while RunService.RenderStepped:Wait() do
updateCountdownDisplay()
if os.time() - countdownStartTime >= totalCountdownDuration then
break
end
end
task.wait(0.1) -- Small delay to ensure the last number is visible
teleportCountdownGui.Enabled = false
countdownLabel.Visible = false
activeCountdownThread = nil
end)
end
-- Function to stop the client-side countdown
local function stopClientCountdown()
if activeCountdownThread then
task.cancel(activeCountdownThread)
activeCountdownThread = nil
end
teleportCountdownGui.Enabled = false
countdownLabel.Visible = false
end
-- Listen for the RemoteEvent from the server
TeleportCountdownEvent.OnClientEvent:Connect(function(action, data)
if action == "start" then
startClientCountdown(data)
elseif action == "stop" then
stopClientCountdown()
end
end)
-- Initialize the GUI when the script starts
setupGui()
Summary of Changes:
The LocalScript now dynamically creates the ScreenGui and TextLabel objects using Instance.new() and sets their properties.
The setupGui() function is called once at the start of the LocalScript to build the GUI.
teleportCountdownGui.ResetOnSpawn = true is explicitly set, which is crucial for GUIs created in StarterGui if players can respawn.
Now, when you play the game, the GUI will be created by the script, and the countdown will appear when you stand on the "teleport" part!