I was wondering if there is a function like KeyDown
, except KeyHold
or something like that so while your holding the key it can do a function instead of having to do KeyDown
then KeyUp
. Can anyone tell me if there is a function I can use to achieve this?
DragonODeath is making UserInputService too complicated. Here is how it works. If you want to see if a key is pressed use KeyCode.
local uis = game:GetService("UserInputService") uis.InputBegan:connect(function(key, processed) if key.KeyCode == Enum.KeyCode.Space and not processed then print("Pressed space") end end)
Processed is like chatting or typing into a textbox.
To find any key pressed use
local uis = game:GetService("UserInputService") uis.InputBegan:connect(function(key, processed) if not processed then print("Pressed key") end end)
You can use UserInputService to see if someone clicked using UserInputType.
local uis = game:GetService("UserInputService") uis.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then print("Left clicked") end end)
You can find the rest of the enums here.
There is no "Hold" event with UserInputService so we would have to make a variable true and loop until the variable is false, we set it to false using InputEnded
!
local uis = game:GetService("UserInputService") local activated = false uis.InputBegan:connect(function(key, processed) if key.KeyCode == Enum.KeyCode.A and not processed then --pressed A activated = true repeat print("Pressed A!") until not activated end end) uis.InputEnded:connect(function(key, processed) if key.KeyCode == Enum.KeyCode.A and not processed then activated = false end end)
Hope it helps!
KeyDown was recently deprecated. Due to this, you must use UserInputService. If you want to tell when somebody is holding a key, you would use InputBegan and run your code until InputEnded is triggered by them letting go of the key. If you are looking for a specific key, you could use KeyCodes to determine what key is being held in.
Following FearMeIAmLag's answer, using InputBegan
and InputEnded
, you can safely assume that a key is held down after InputBegan
and that it's released after InputEnded
. Furthermore, it is possible to know what key is being pressed via the KeyCode property of the InputObject. So, to exemplify, look at the following code:
local userInputService = game:GetService('UserInputService') local F_keydown = false local function OnKeyDown(key) if key == Enum.KeyCode.F then F_keydown = true while F_keydown do wait(1) print'The F key is being pressed !' end end end local function OnKeyUp(key) if key == Enum.KeyCode.F then F_keydown = false end end userInputService.InputBegan:connect( function(InputObj) OnKeyDown(InputObj.KeyCode) end ) userInputService.InputEnded:connect( function(InputObj) OnKeyUp(InputObj.KeyCode) end )