I’m using UserInputService, I know how to check if a key was pressed, but I’m not sure how to tell if it’s being held down, how would I do that? How would I check if It weren’t held anymore too?
You can use the :IsKeyDown()
method of UserInputService. Just pass the key you want and :IsKeyDown()
will return true if the key is being held down, false otherwise.
local UserInputService = game:GetService("UserInputService") UserInputService.InputBegan:Connect(function(input, gpe) if gpe then return end if input.UserInputType == Enum.UserInputType.MouseButton2 then -- you can detect mouse input if UserInputService:IsKeyDown(Enum.KeyCode.E) then -- Code end end end)
First, insert a LocalScript into the StarterPlayerScripts in the StarterPlayer. Remove the print function and replace it with this:
local UserInput = game:GetService("UserInputService") -- So we can fire the function below local function inputR(inputObject, gameProcessedEvent) end UserInput.InputBegan:Connect(inputR)
Now insert a simple if statement inside the local function with a return.
local UserInput = game:GetService("UserInputService") -- So we can fire the function below local function inputR(inputObject, gameProcessedEvent) if gameProcessedEvent then return end -- I did it this way so it doesn't take up space. end UserInput.InputBegan:Connect(inputR)
Now make sure the user has a keyboard, so no weird errors occur.
local UserInput = game:GetService("UserInputService") -- So we can fire the function below local function inputR(inputObject, gameProcessedEvent) if gameProcessedEvent then return end if inputObject.UserInputType == Enum.UserInputType.Keyboard then end end UserInput.InputBegan:Connect(inputR)
Now test the key you would like to be pressed. I Added more comments to make more clear.
local UserInput = game:GetService("UserInputService") -- So we can fire the function below local function inputR(inputObject, gameProcessedEvent) if gameProcessedEvent then return end if inputObject.UserInputType == Enum.UserInputType.Keyboard then -- So we know that the player is holding down a key on their keyboard instead of a fake one if inputObject.KeyCode == Enum.KeyCode.R then -- Replace "KeyCode.R" with any other key, for example, left shift is "Enum.KeyCode.LeftShift". -- --Do code for your key pressed here end end end UserInput.InputBegan:Connect(inputR) -- So we can fire the function when any key/mouse is pressed. Anything else will also fire the function, like gamepad.
I hope this was helpful!