How To Stop Animation After It's Finished Playing

Hi, I recently made an animation and coded it so that it would play on the key pressed “Q”. I only know how to make this animation run in an if loop and not a single function or to stop the animation after it it finished playing. Here is the script,

local UserInputService = game:GetService("UserInputService")
local Animation = script.Animation

UserInputService.InputBegan:Connect(function(Input)
	if Input.KeyCode == Enum.KeyCode.Q then
		local player = game.Players.LocalPlayer
		local character = player.Character
		local Humanoid = character:WaitForChild("Humanoid")
		
		local Anim = Humanoid:LoadAnimation(Animation)
		Anim:Play()
	end
end)

Everything works except I would like the animation to run only once when Q is clicked.

1 Like

Could a debounce be a good solution?

local UserInputService = game:GetService("UserInputService")
local Animation = script.Animation

local didPlay = false

UserInputService.InputBegan:Connect(function(Input)
    if didPlay then return end

	if Input.KeyCode == Enum.KeyCode.Q then
		local player = game.Players.LocalPlayer
		local character = player.Character
		local Humanoid = character:WaitForChild("Humanoid")
		
		local Anim = Humanoid:LoadAnimation(Animation)
		Anim.Play()
                didPlay = true
	end
end)
2 Likes

The script worked however would not let me play the animation again after.

1 Like

Isn’t that what you wanted? I’m kinda confused, you only want it to play once?

1 Like

I only want it to play one time (not permanently) when Q is clicked, not looped.

1 Like

Just make it so your animation isn’t looped, try this:

local UserInputService = game:GetService("UserInputService")
local Animation = script.Animation

local player = game.Players.LocalPlayer
		local character = player.Character or player.CharacterAdded:Wait()
		local Humanoid = character:WaitForChild("Humanoid")
		
		local Anim = Humanoid:LoadAnimation(Animation)
Anim.Looped = false

UserInputService.InputBegan:Connect(function(Input)
	if Input.KeyCode == Enum.KeyCode.Q then
		
		Anim:Play()
	end
end)
1 Like

add anim:Stopped event to know if animation stop played then make didPlay = false Stopped ( )

2 Likes

It gives me this annoying error,

like that

1. animationTrack.Stopped:wait()
2. print("Animation has stopped") ```
2 Likes

I’ve modified the code for you.

2 Likes

Stopped() Fires whenever the AnimationTrack finishes playing.

1 Like

Thanks, I’m not so good at scripting but I much appreciate your constant help.

1 Like

You forgot to toggle the debounce once enabling it.

1 Like

I thought he meant he only wanted it to play once, so that’s why I did that.