Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Need help with activating a function while I'm hold a key down?

Asked by 5 years ago

I'm trying to move a part forward while I'm HOLDING a key W. When I release button W then part shouldn't go forward. How could I possibly do it? Please help me

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

To run a function while holding a key you'll want to use the repeat loop and a simple boolean variable. Doing this, once you start holding the key, the loop will run until you stop holding the key. As seen here:

local holdingW = false
local userInputService = game:GetService("UserInputService")

userInputService.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.W then
        holdingW = true -- Being loop:

        repeat
            wait(0.2)
            print("Is holding W")
        until holdingW == false
    end
end)

userInputService.InputEnded:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.W then
        holdingW = false -- End loop.
    end
end)

As you can see the loop will run until it detects a change within the variable. Even when made outside of the loop.

0
Omg it worked. Thank you iCROTony -1 — 5y
0
Welcome bro namespace25 594 — 5y
0
nice answer lon233bcc 31 — 5y
Ad

Answer this question