I am currently working on making a few keybinds for my game’s tutorial, however when I start spamming Q and E (next/prev respectively), it doesn’t always return the correct input. I am not sure why, I will show the output below, you can tell when p/n starts piling up. Keep in mind that I am alternating Q and E, Q should return p (previous), and E should return n (next).
Here’s my script (excuse my horrible variable names)
Summary
local u = game:GetService("UserInputService")
local p = Enum.KeyCode.Q
local n = Enum.KeyCode.E
u.InputBegan:Connect(function(k, g)
if pb() then
print("p")
--prev
elseif nb() then
print("n")
--next
end
end)
function pb()
return u:IsKeyDown(p)
end
function nb()
return u:IsKeyDown(n)
end
Your script wont progress beyond the line if pb() because that will always have a value returned meaning that it will always return true so it will not progress onto the elseif part of your code
You could make this script a lot more efficient and reliable by using a format like below:
local UIS = game:GetService('UserInputService')
local p = Enum.KeyCode.Q
local n = Enum.KeyCode.E
UIS.InputBegan:Connect(function(key,CanWork)
if not CanWork then -- Checking if user is typing
if key.KeyCode == p then -- Checking if the key = Q
print('p')
elseif key.KeyCode == n then --- Checking if the key = E
print('n')
end
end)
To add additional keybinds all you would need to do is add another elseif statement
This will be far more efficient as it is all dealt with in one function rather than having to call and return values each time you want to check which key is being checked
When using UserInputService and you call the function InputBegan two values will be returned:
The first Key is the key being input by the user
The second CanWork is a bool value that is returned. If the action is a GameProcessedEvent such as the user is typing in chat or a text box, it will return true and if not it will return false.
By checking this you stop the event being triggered whilst a user is typing or interacting with a textbox and is used by developers to prevent the firing of events when a user is just typing a sentence.
You can read more about it here on the API: