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

How to make an animation stop early on key release?

This is the code that makes a new animation, and plays it on key down.

			 blockanime = Instance.new("Animation")
		blockanime.AnimationId = "http://www.roblox.com/asset/?id=1933843521" --- type here the animation ID
		local animloader = Player.Character.Humanoid:LoadAnimation(blockanime)
		animloader:Play()

And this is the key release function.

uis.InputEnded:connect(function(input,process)--Stop blocking
        if input.KeyCode == Enum.KeyCode.R then
if not process then
        blocking = false 
       wait()
Player.Character.Humanoid.WalkSpeed = 16
		local animloader = Player.Character.Humanoid:LoadAnimation(blockanime)
		animloader:Stop()
    end
end
end)

I also tried :Destroy()ing blockanime on key release, but that didn't work, so I just copying the code that plays it, and replacing :Play() with :Stop()

1 answer

✓ Accepted answer

What you need to be doing is keeping a reference to the playing animation in the same scope to where both the InputBegan and InputEnded connected functions can access it.

local animloader = nil -- initially nil

uis.InputBegan:Connect(function(input, process)
	blockanime = Instance.new("Animation")
	blockanime.AnimationId = "http://www.roblox.com/asset/?id=1933843521" 
	local animloader = Player.Character.Humanoid:LoadAnimation(blockanime)
	animloader:Play()
end)

uis.InputEnded:Connect(function(input, process)
	if animloader then -- make sure the animation exists
		animloader:Stop()
	end
end)

Notice how the animloader variable is outside and above both the InputBegan and InputEnded event connections. This gives them both access to it, allowing you to Play() and Stop() in different scopes within your code.

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