Keyboard Input Methods
Keyboard Input Methods
Keyboard input can be obtained in Roblox through one of two services: UserInputService
andContextActionService
. Of the two, ContextActionService is recommended as it can be easily used to bind other input types.
ContextActionService
ContextActionService
binds a set of inputs to a function. To bind a function to a keyboard button with this service, call the function ContextActionService/BindAction
.
For example, to print a string when the R key is pressed, a function can be bound like so:
function onKeyPress(actionName, userInputState, inputObject)
if userInputState == Enum.UserInputState.Begin then
print("R was pressed")
end
end
game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.R)
-- The above line could also been written as:
-- game.ContextActionService:BindAction("keyPress", onKeyPress, false, "r")
It is important to note that a function bound through BindAction will fire on all state changes of the input (began, ended, changed). If you want your function to execute on a particular input state, it is important to check for that through the inputObject which is passed into the bound function.
UserInputService
UserInputService
binds functions to input via its events, such as UserInputService/InputBegan
or UserInputService/InputEnded
. These events fire on any input change, so it is important to check for the particular input you are interested in when handling the function.
For example, to print a string when the R key is pressed, a function can be bound like so:
function onKeyPress(inputObject, gameProcessedEvent)
if inputObject.KeyCode == Enum.KeyCode.R then
print("R was pressed")
end
end
game:GetService("UserInputService").InputBegan:connect(onKeyPress)