How to detect if user is holding key for X seconds

Hello there.

I am wanting to know if it is possible to be able to hold a key for a certain amount of seconds for a UI to pop up when you are close to it, instead of clicking or normally pressing a key. Does anyone know how to do that?

9 Likes

You could do something along these lines:

local HELD_TIME = 0.5

local counter = 0 -- index of current action
local active = false -- current state

ContextActionService:BindAction(
	"TestAction",
	function(_, state, _)
		if state == Enum.UserInputState.Begin then
			active = true
			counter = counter + 1
			local copy = counter
			wait(HELD_TIME)
			if active and copy == counter then
				-- button is still down and hasn't been unpressed/pressed inbetween
				doAction()
			end
		elseif state == Enum.UserInputState.End then
			active = false
		end
	end,
	false,
	-- add your input here
	Enum.KeyCode.Q -- example
)
7 Likes

I would use UserInputService as the input object includes a changed event meaning that the whole code logic can be kept within the event itself.

local i = 0
game:GetService("UserInputService").InputBegan:Connect(function(inpObj, gp)
	if inpObj.KeyCode == Enum.KeyCode.LeftShift then
		i = i + 1
		local tmpVal = i
		print(tmpVal, "Shift pressed down")
		
		local held = true
		local con
		con = inpObj.Changed:Connect(function(prop)
			if prop == "UserInputState" then
				con:Disconnect() -- prevent spam
				held = false
				print(tmpVal, "Shift released")
			end
		end)
		
		wait(5)
		
		if held then
			print(tmpVal, "Shift held")
		end

	end
end)
33 Likes

It worked, thank you so much!