For example, if I want to find out if a player is holding down the "U" key, how would you do it?
P.S: The previous scripts found in the site did NOT work.
Thanks!
There are multiple ways. I'm going to use UserInputService
's InputBegan and InputEnded events.
You didn't provide what you wanted to do when they're holding a button, but I'l just run a loop.
-- Local Script: local UIS = game:GetService("UserInputService") local holdingUKey = false -- Detect input began UIS.InputBegan:Connect(function(inputObject) -- Check if input is the U key. if(inputObject.KeyCode==Enum.KeyCode.U)then -- make variable true holdingUKey = true -- Run loop until variable is false while holdingUKey do print("Holding u key!") wait(0.2) end end end) -- Detect input ended UIS.InputEnded:Connect(function(inputObject) -- Check if input lost was the U key. if(inputObject.KeyCode==Enum.KeyCode.U)then -- make variable false holdingUKey = false end end)
I commented everything, but if you have any questions let me know.
There is a function on UserInputService
which tells you which keys are currently being pressed. It returns a table of InputObject
s which you can search to see if your key is in there.
InputObject
has a field KeyCode
which corresponds to the pressed key. You can see a table of KeyCode values here.
Thankfully, there is an even more specific function called IsKeyPressed()
so that you don't even have to search the list yourself!
Have a look at the API for UserInputService
on the official ROBLOX wiki. The function IsKeyPresed()
is what you're looking for.
Just pass in the appropriate KeyCode value for the U key and voila!
-- Get a reference to the UserInput Service input_service = game:GetService("UserInputService") is_u_down = input_service:IsKeyDown(Enum.KeyCode.U)