pretty much as the title describes, im trying to make an if statement using userinputservice and enum.keycode to check whether a player holds or taps the F key. but i dont really know how. that’s about it.
local UserInputService = game:GetService("UserInputService")
UserInputService.InputBegan:Connect(function(input, gameproccessed)
if input.KeyCode == Enum.KeyCode.F then
--the code here will run when someone presses f
end
end)
Just check if it is Enum.KeyCode.Key
i probably should’ve been a bit more clear, i meant to say that i know how to define when a player is pressing a key, but not holding one. and i need to run two specific pieces of codes based on whether or not it’s held or tapped.
Almost the same as above, but with additional parameters:
local UserInputService = game:GetService("UserInputService")
local PresKey = false
local UpKey = false
UserInputService.InputBegan:Connect(function(input, gameproccessed)
if input.KeyCode == Enum.KeyCode.F then
--the code here will run when someone presses f
while wait() do
if UpKey == false then
PresKey = true
elseif UpKey == true then
PresKey = false
UpKey = false
print("EndPress")
break
end
end
end
end)
UserInputService.InputEnded:Connect(function(input, gameproccessed)
if input.KeyCode == Enum.KeyCode.F then
print("EndPres")
UpKey = true
end
end)
ok i just clicked solution since i had to go and i skimmed over, but on second thought where am i supposed to implement the code that is supposed to run if upkey = true?
i understand pressing but i have no idea how to run code if the key is being held
It all depends on what needs to be done. It can be implemented either like in this script or in another one. However, if it’s in another script, you would need to use either a BindableEvent or a separate BoolValue.
I’m just a bit unclear about how to explain it, because I don’t understand the underlying idea of why the key press check is needed.
As a straightforward example, it could be triggering an event when a button in a GUI window is clicked, similar to this.
local UserInputService = game:GetService("UserInputService")
local PresKey = false
local UpKey = false
local Button = script.Parent
UserInputService.InputBegan:Connect(function(input, gameproccessed)
if input.KeyCode == Enum.KeyCode.F then
--the code here will run when someone presses f
while wait() do
if UpKey == false then
PresKey = true
elseif UpKey == true then
PresKey = false
UpKey = false
print("EndPress")
break
end
end
end
end)
UserInputService.InputEnded:Connect(function(input, gameproccessed)
if input.KeyCode == Enum.KeyCode.F then
print("EndPres")
UpKey = true
end
end)
Button.MouseButton1Click:Connect(function()
if PresKey == true then
print("ClickButton")
end
end)