Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would you make an event that functions while holding down a key?

I know how to make something happen when you press a key, but how would you make it so that it only happens while your holding that key down?

For example, while your'e holding down e, your character is playing an animation, from a script in a tool, but when you let go of e, your character stop playing the animation.

2 comments

0

Try using the context action service

0

Can you expand a little? Maybe add a link to the roblox wiki about that?

1 answer

✓ Accepted answer

Here's some code based on your example

local UserInputService = game:GetService("UserInputService")

local ACTIVATION_KEY = Enum.KeyCode.E
local ANIMATION_ID = "http://www.roblox.com/Asset?ID=144884906"

local animationTrack
local animation = Instance.new("Animation")
animation.AnimationId = ANIMATION_ID

UserInputService.InputBegan:Connect(function(input)
    if input.KeyCode == ACTIVATION_KEY then
        local character = game.Players.LocalPlayer.Character
        if character then
            animationTrack = character.Humanoid:LoadAnimation(animation)
            animationTrack:Play()
            if not animationTrack.Looped then
                animationTrack.DidLoop:Connect(function()
                    animationTrack:Play()
                end)
            end
        end
    end
end)

UserInputService.InputEnded:Connect(function(input)
    if input.KeyCode == ACTIVATION_KEY then
        if animationTrack then
            animationTrack:Stop()
            animationTrack = nil
        end
    end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.