Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I execute a script when a key is held for some time?

So, I want to learn how to execute a chunk of code when a player presses and holds a key but i'm not sure how to approach this, any help?

player = game.Players.LocalPlayer
mouse = player:GetMouse()

mouse.KeyDown:connect(function(key)
	print(key:byte())
	if key == "f" then
		print("wassup")
	else
		print("hi")
	end
end)

1 answer

✓ Accepted answer

All you have to do is use a while loop to keep track of the time the key has been pressed. You also have to detect when the key has been "un-pressed" to reset that time. Like this :

player = game.Players.LocalPlayer
mouse = player:GetMouse()
fPressed = false
timePressed = 0

mouse.KeyDown:connect(function(key)
    if key == "f" then
		fPressed = true
    end
end)

mouse.KeyUp:connect(function(key)
    if key == "f" then
		fPressed = false
		timePressed = 0
    end
end)

while true do
	if fPressed then
		timePressed = timePressed + wait()
		if timePressed > 3 then
			print("F has been held for three seconds")
		end
	else
		wait()
	end
end

3 comments

0

Impressive, but when I stop holding after the '3 second mark' it continues back where it left off. Very appreciated though!

0

One more thing, is there way to stop the 'spam' it causes when you have held the key for more then 3 seconds?

0

To fix that, just add a protection on line 20 that checks if your function has already been activated. Or, at line 23, just reset timePressed and set fPressed to false ;)

This discussion is preserved as it was. New answers, comments, and votes are closed.