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!
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 InputObjects 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)
Why are you not using Local Variables?
I didn't want to muddy the excerpt with unnecessary qualifiers - the performance benefits of local variables are not relevant to the question.
This discussion is preserved as it was. New answers, comments, and votes are closed.
3 comments
This detects when a player begins and stops holding a key, but doesn't answer the question about checking whether a key is already held.
That wasn't the question. The question was , if I want to find out if a player is holding down the "U" key, how would you do it?. You can use IsKeyDown, but that doesn't answer if they're holding down the key for any length of time, only if the key is down when the statement is called. There might be two ways to interpret the question.
True, querying IsKeyDown() at every moment where holdingUKey would be used would yield the same value - unless your script starts after the key is pressed, in which case holdingUKey won't have the right value.