Checking how much time a key is held

Hello, I’m looking for a way to detect how much time a key is held, like for doing charging skills or for a bow. I don’t really know how to do it, I have a script that only detects if a key is held for a certain amount of time.

Search first before posting threads please.
https://devforum.roblox.com/search?q=hold%20key%20category%3A55

Those topics didn’t help for my objective, I want to check a variable amount of time while the key is held, not IF a key is held that amount of time.

1 Like

The time() function returns the number of seconds the game has been running. You could set up an event to store the time value when the key was pressed down as a variable, then compare that to the time the key was released.

local uis = game:GetService("UserInputService")
local timeStarted = 0
uis.InputBegan:Connect(function(input, gpe)
    if (input.UserInputType == Enum.UserInputType.Keyboard) then
        if (input.KeyCode == Enum.KeyCode.E) then -- Or whatever key or input you want
            timeStarted = time()
        end
    end
end)
uis.InputEnded:Connect(function(input, gpe)
    if (input.UserInputType == Enum.UserInputType.Keyboard) then
        if (input.KeyCode == Enum.KeyCode.E) then -- Same key
            print("Time key was held: "..(time() - timeStarted).." seconds.")
        end
    end
end)
3 Likes

Hello just to clarify, does it really count in seconds because it seems to be a bit slow for it to be counted in seconds