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

How can you detect if a player has held down a key for a period of time?

Asked by 7 years ago

I am trying to make a player hold down a key for a set amount of time, and then when that is over, it runs a line of code.

So far, I wasn't able to find anything on the wiki for this.

1 answer

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

You can do it with this code. I also included the mouse key in case you need it. The script MUST be a local script, otherwise, it won't work !

Player = game.Players.LocalPlayer
Mouse = Player:GetMouse()


-- For Mouse button (Left Click)
MouseHoldTime = 0
MouseHolding = false
MouseTimeToHold = 10 -- Change this to the number of seconds that the player must be holding the mouse to call the desired function.

Mouse.Button1Down:connect(function()
    MouseHolding = true
    repeat
        wait(1)
        if MouseHolding == true then
            MouseHoldTime = MouseHoldTime +1
            if MouseHoldTime == MouseTimeToHold then
                -- Stuff
                print("Holded the mouse for "..MouseTimeToHold.." seconds.") -- This is an example.
            end
        end
    until MouseHolding == false
end)

Mouse.Button1Up:connect(function()
    MouseHolding = false
    print("Holded the mouse for "..MouseHoldTime.." seconds.")
    MouseHoldTime = 0
end)


-- For Key button (Key Pressed)
KeyHoldTime = 0
KeyHolding = false
KeyToHold = "c" -- Change this to the key that the player must be holding to launch the timer.
KeyTimeToHold = 10 -- Change this to the number of seconds that the player must be holding the key to call the desired function.

Mouse.KeyDown:connect(function(Key)
    if Key == KeyToHold then
        KeyHolding = true
        repeat
            wait(1)
            if KeyHolding == true then
                KeyHoldTime = KeyHoldTime +1
                if KeyHoldTime == KeyTimeToHold then
                    -- Stuff
                    print("Holded the "..KeyToHold.." key for "..KeyTimeToHold.." seconds.") -- This is an example.
                end
            end
        until KeyHolding == false
    end
end)

Mouse.KeyUp:connect(function(Key)
    if Key == KeyToHold then
        KeyHolding = false
        print("Holded the "..KeyToHold.." key for "..KeyHoldTime.." seconds.")
        KeyHoldTime = 0
    end
end)
Ad

Answer this question