Tool Held Down LocalScript

  1. What do you want to achieve?
    I want to create a script that runs on tool and checks how long it is held down

  2. What is the issue?
    I have no idea how it would check that I was using the tool and check how long it was held down

  3. What solutions have you tried so far?
    Roblox forum, youtube, roblox documentation

2 Likes
local start_time

local end_time

script.Parent.Equipped:Connect(function(mouse)
	
	mouse.Button1Down:Connect(function()
		
		start_time=tick()
		
	end)
	
	mouse.Button1Up:Connect(function()
		
		end_time=tick()
		
		local time_taken=(end_time-start_time)
		
		print(math.round(time_taken))
		
	end)
end)

There is a way out of this, and if I wanted to automatically terminate a hold after e.g. 2 seconds

So you want to end the script after the players holds down for 2 seconds?

Exactly as you wrote ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

Okay, I got it, thanks for your help.

local start_time
local end_time
local max_holding_time = 2
local holding = false

script.Parent.Equipped:Connect(function(mouse)
	mouse.Button1Down:Connect(function()
		if holding then return end

		holding = true
		start_time = tick()

		while holding do
			local current_time = tick() - start_time
			if current_time >= max_holding_time then
				
				print("Limit time")
				holding = false 
				
				break
			end
			wait(0.1)
		end
	end)

	mouse.Button1Up:Connect(function()
		if not holding then return end

		holding = false
		end_time = tick()

		local time_taken = math.min(end_time - start_time, max_holding_time)
		print(math.round(time_taken) .. " seconds")
	end)
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.