Holding down a button

I need to know when a button is held down. In my case Left Shift. I can easily do this via:

local ShiftPressed = false

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		ShiftPressed = true
	end
end)
UIS.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		ShiftPressed = false
	end
end)

But I dont like this dual connection to change the variable when the key is released. So I thought of someway to do it using only one Connection. After a while I came up with this:

local ShiftPressed = false

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		ShiftPressed = true
		UIS.InputEnded:Wait()
		ShiftPressed = false
	end
end)

This worked, but unfortunately if any other key was released while shift was held down. It would register and ShiftPressed would become false, even when Shift was still held down. I couldn’t think of any way to add a condition to the wait so it would only stop waiting when shift was released.
Is there any way to do this, or am I stuck with the first option?

2 Likes

you can do this

input:GetPropertyChangedSignal("UserInputState"):Once(function()
      ShiftPressed = false
end)
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.