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

How can the Client hold down a key that plays the animation without it constantly playing?

What my problem here is that when ever I hold down the S key, (it plays an animation) it constantly plays from the start which I find really annoying. I'm not sure how I'm going to do this.

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local humanoid = player.Character.Humanoid
local anim = Instance.new("Animation")
anim.AnimationId = "http://www.roblox.com/asset/?id=3398376417"
local holdingSKey = false

UIS.InputBegan:Connect(function(inputObject) 
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = true
        while holdingSKey do
	    local playAnim = humanoid:LoadAnimation(anim)
		playAnim:Play()
            wait(0.2)
        end
    end
end)

UIS.InputEnded:Connect(function(inputObject)
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = false
    end
end)

2 answers

AnimationTracks have an IsPlaying property. Create your animation track variable (playAnim) outside of the event and you should be able to use this property.

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local humanoid = player.Character.Humanoid
local anim = Instance.new("Animation")
anim.AnimationId = "http://www.roblox.com/asset/?id=3398376417"
local holdingSKey = false

local playAnim = humanoid:LoadAnimation(anim)

UIS.InputBegan:Connect(function(inputObject) 
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = true

        while holdingSKey do
		--Check if the animation is playing, if it's not, play the animation again
		if(not playAnim.IsPlaying)then
	      		playAnim:Play()
	         	wait(0.2)
		end
        end
    end
end)

UIS.InputEnded:Connect(function(inputObject)
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = false
    end
end)

You could simply use the AnimationTrack.Looped property for this case:

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local humanoid = player.Character.Humanoid
local anim = Instance.new("Animation")
anim.AnimationId = "http://www.roblox.com/asset/?id=3398376417"
anim = humanoid:LoadAnimation(anim)
anim.Looped = true

UIS.InputBegan:Connect(function(inputObject) 
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        anim:Play() -- This will keep looping until stopped
    end
end)

UIS.InputEnded:Connect(function(inputObject)
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        anim:Stop() -- Simply stop the looping
    end
end)

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