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
✓ ANSWER ACCEPTED
Need help with activating a function while I'm hold a key down?
1 answer
✓ Accepted answer
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.
This discussion is preserved as it was. New answers, comments, and votes are closed.

3 comments
Omg it worked. Thank you
Welcome bro
nice answer