Hello guys. Im trying to make a script that if the player touches a part, then a UI will show, countdown from 5 to 0 and then teleport him to another place.
My problem is, how do i stop it from executing in case the player stops touching a part.
local GUI = player.PlayerGui.ScreenGui.TPNotification
local text = GUI.TextLabel
local duration = 5
local stoppedtouching = false
local function Teleport(trigger: Part, part : Part, placeID : number)
if part.Parent == player.Character then
GUI.Visible = true
while duration > 0 do
GUI.TextLabel.Text = "Teleporting in:".. duration
duration =- 1
if stoppedtouching then
GUI.Visible = false
duration = 5
return
end
wait(1)
end
local touchingParts = trigger:GetTouchingParts()
for i, part in touchingParts do
if part.Parent == player.Character then
TeleportService:Teleport(placeID, player)
end
end
end
GUI.Visible = false
duration = 5
end
island1Trigger.Touched:Connect(function(part)
Teleport(island1Trigger, part , island1ID)
end)
island1Trigger.TouchEnded:Connect(function(part)
if part.Parent == player.Character then
stoppedtouching = true
GUI.Visible = false
duration = 5
end
end)
What happens here is that it doesnt really do a countdown and when the player leaves it doesnt reset as to stop from teleporting.
TeleportService:Teleport(placeID, player) also does not respect the yield on wait. It just goes
You could have a table for players who are touching the part in a table and when they stop touching the part it will remove them from the table.
Example script below:
local TABLE = {}
game.Workspace.Part.Touched:Connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit) then
local Player = game.Players:GetPlayerFromCharacter(hit)
table.insert(TABLE, Player.UserId)
end
game.Workspace.Part.TouchedEnded:Connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit) then
local Player = game.Players:GetPlayerFromCharacter(hit)
table.remove(TABLE, table.find(TABLE, Player.UserId))
end
end)
for i = 5, 1, -1 do
-- update gui text
task.wait(1)
end -- this will run 5 times and each time i will decrease by 1, since the code after a for loop only runs once the for loop is done this will both wait 5 seconds and update the gui every second
local player = --get the player
if touching and player then
-- teleport the player
end
You will just need to properly handle touched events and update the touching variable accordingly.