UserInputService.InputBegan:Connect(function (InputObject, GameProcessedEvent)
if not GameProcessedEvent then
if InputObject.UserInputType == Enum.UserInputType.Keyboard then
if InputObject.KeyCode == Enum.KeyCode.LeftShift then
if UserInputService:IsKeyDown(Enum.KeyCode.S) then
print("S")
elseif UserInputService:IsKeyDown(Enum.KeyCode.W) then
print("W")
end
end
end
end
end)
Right now, I’m trying to script a system that will make a player do something if they press shift while W or S is held down. The code I’m using is above. Assuming the print means the function is called, the function is called three times. How do I get it to run only once?
The way I set up the code is mostly intentional. Shift + S takes precedence over Shift + W.
A debounce is intended to make its presence here, which I’m certain will solve the problem of the above running three times. I’m wondering though; is there a way to make the above fire only once without said debounce, or is there no point in knowing that?
Wait wouldn’t solve the problem; it’d just stall how long before it gets printed again.
The way you have set it up is that it will only run when shift is pressed and the keys are already down – meaning if the player pressing shift then pressing one of those other keys, it won’t run.
So to get best experience for your players you’d want to do something like this:
Code
local PressedS = false
local PressedW = false
local PressedShift = false
local function Check()
if PressedS and PressedShift then
-- s
elseif PressedW and PressedShift then
-- w
end
end
UserInputService.InputBegan:Connect(function (InputObject, GameProcessedEvent)
if not GameProcessedEvent then
if InputObject.UserInputType == Enum.UserInputType.Keyboard then
if InputObject.KeyCode == Enum.KeyCode.LeftShift then
PressedShift = true
Check()
elseif InputObject.KeyCode == Enum.KeyCode.S then
PressedS = true
Check()
-- etc.
end
end
end
end)
you need to make sure when you’re coding that you use the right functions for what you’re trying to achieve. If you have the key down then it will repeatedly print. Make sure it’s only printing for the key going down once.
I tried the same thing and it only printed once for me. Are you sure there is only one copy of the script in your game? Otherwise this sounds like a bug, because the event should only fire once.
I suspect your keyboard might be sending Enum.UserInputState.Change events while you hold down, so try adding a check for InputObject.UserInputState being Enum.UserInputState.Begin
@TheGamer101@colbert2677 This is the intended behaviour.
I also encountered this problem while I was an Accelerator and filed it as a bug.
It turned out that it was the event firing with the different InputStates (begin, change, end).
You can use InputObject.UserInputState to check the current state.