Hey guys. So I made a timer that starts when you touch a part and ends when you touch another (used to know your time on an obby).
That timer runs on every single client whenever one client touches a part, and I need help fixing that…
I also need it to be able to display that timer to the textbox (script.Parent.Text). I tried making the print statement script.Parent.Text, although that displayed “ELAPSED” and I don’t know why… Please help! Thank you.
local RunService = game:GetService("RunService")
local connection = nil
workspace.Timer.Touched:Connect(function()
if (connection) then return end -- already running, do nothing
local startTime = tick()
-- create a connection that will run every frame until
-- connection is disconnected in the stop method
connection = RunService.Stepped:Connect(function()
local elapsed = tick() - startTime
local milliseconds = math.floor(1000 * math.fmod(elapsed, 1))
local seconds = math.floor(elapsed % 60)
local minutes = math.floor(elapsed / 60)
-- prints out every single frame
print(string.format("Elapsed time: %d:%.02d.%.03d", minutes, seconds, milliseconds))
end)
end)
workspace.Stop.Touched:Connect(function()
print("Stopped")
if (connection) then
connection:Disconnect()
connection = nil
end
end)
This code fires whenever the timer is touched, so it doesn’t matter who touches it. Basically one player steps on it, and the touched event fires for every local script. Therefore, its not that the local script is firing for everyone, but instead that each local script fires.
2 Likes
Ah… I see… How could I fix that though?
When the player touches, check who touched it and verfiy that it was actually that player. For touched events, the first parameter is what hit the object. In this case the “Hit” variable will be the leg, so we check if the leg’s parent (the character) has the same name as the local player.
local player = game.Players.LocalPlayer
workspace.Timer.Touched:Connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent) then
if hit.Parent.Name == player.Name then
--rest of code here
end
end
end)
workspace.Stop.Touched:Connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent) then
if hit.Parent.Name == player.Name then
--rest of code here
end
end
end)
Edit: I originally had a few typos, if it doesn’t work then try recopying this code I just fixed them.
3 Likes
Thank you very much.
I now need help with this: I need it to be able to display that timer to the textbox (script.Parent.Text). I tried replacing the print statement to script.Parent.Text, although that displayed “ ELAPSED ” and I don’t know why… Please help! Thank you. (@XdJackyboiiXd21 @BenMactavsin)