simple question, is there a way to get while a button is being held
Bound action callbacks are executed at each state transition of the corresponding action. Roblox provides you context through the UserInputState enum, which is received in the second parameter of the callback. You can implement the following code to create a persistent process while an input has yet to be released:
local process
local function handleAction(_, state: Enum.UserInputState, input: InputObject)
if state == Enum.UserInputState.End then
task.cancel(process)
return
end
if state ~= Enum.UserInputState.Begin then
return
end
process = task.defer(function()
while true do
-- ...
task.wait()
end
end)
end
ContextActionService:BindAction("Example", handleAction, false, Enum.KeyCode.E)
Though the code is not functionally equivalent in the sense that you can cancel the process at any yielding point, you can achieve a simpler version of the above code through the UserInputService:IsKeyDown function:
local function handleAction(_, state: Enum.UserInputState, input: InputObject)
if state ~= Enum.UserInputState.Begin then
return
end
while UserInputService:IsKeyDown(input.KeyCode) do
-- ...
task.wait()
end
end
You can alternatively use UserInputService.InputBegan for this code example
1 Like