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

How do I stop an animation from playing? (UserInputSettings)

**Greetings,

I have been trying to make an animation load when a certain key is pressed. Succeeded, however, my problem is how do I make the same animation stop if the same key is pressed? It is a meditating animation.

I put the script down below. I would really appreciate some help.

Best wishes, Amydamaru**

local player = game:GetService("Players").LocalPlayer

local character = player.Character or player.Character:Added()

local humanoid = character:WaitForChild("Humanoid")

local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://375479668"

function playAnimation(Anim)
    local track = humanoid:LoadAnimation(Anim)
    track:Play()
end

game:GetService("UserInputService").InputBegan:connect(function(input ,proc)
    if not proc then
        if input.KeyCode == Enum.KeyCode.F then
            playAnimation(anim)
        end
    end
end)

1 answer

✓ Accepted answer

You'll need to call the Stop() method on the currently playing AnimationTrack.

local player = game:GetService("Players").LocalPlayer

local character = player.Character or player.Character:Added()

local humanoid = character:WaitForChild("Humanoid")

local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://375479668"

local track
function playAnimation(Anim)
    track = humanoid:LoadAnimation(Anim)
    track:Play()
end

game:GetService("UserInputService").InputBegan:connect(function(input ,proc)
	if not proc then
		if input.KeyCode == Enum.KeyCode.F then
			if track then -- track already exists
				if track.IsPlaying then -- track is playing, stop and destroy
					track:Stop()
					track:Destroy()
					track = nil
				else -- track already ended, destroy, create, and play again
					track:Destroy()
					playAnimation(anim)
				end
			else -- track doesn't exist, create and play
				playAnimation(anim)
			end
		end
	end
end)

1 comment

0

Thank you very much for your help.

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