Holding tool animation not stopping after unequipped

I am trying to make a simple sword script and when I unequip the tool the animation is still stuck playing on my character. Here is the code:

local CanAttack = true

script.Parent.Equipped:Connect(function()
	local idle = script.Parent.Parent.Humanoid:LoadAnimation(script.Hold)
	local attack1 = script.Parent.Parent.Humanoid:LoadAnimation(script.Attack1)
	local attack2 = script.Parent.Parent.Humanoid:LoadAnimation(script.Attack2)

	idle:Play()
end)

script.Parent.Activated:Connect(function()
	local idle = script.Parent.Parent.Humanoid:LoadAnimation(script.Hold)
	local attack1 = script.Parent.Parent.Humanoid:LoadAnimation(script.Attack1)
	local attack2 = script.Parent.Parent.Humanoid:LoadAnimation(script.Attack2)

	
	if CanAttack == true then
		local attacks = {attack1, attack2}
		local chosenattack = attacks[math.random(1, #attacks)]
		chosenattack:Play()
		idle:Stop()
		CanAttack = false
		wait(1)
		chosenattack:Stop()
		idle:Play()
		CanAttack = true
		script.Parent.CanDamage.Value = true
	end
end)

script.Parent.Unequipped:Connect(function()
	local idle = game.Workspace:FindFirstChild(game.Players.LocalPlayer.Name).Humanoid:LoadAnimation(script.Hold)
	
	idle:Stop()
end)

Sorry the formatting is bad I’ve never posted on here

From what I see it looks like you’re redeclaring variables for every function. Set a global value for ‘idle’, assign the loaded animation to that, and then reference it. Your code is technically calling a loaded animation value. (Because you’re not looking for it, you’re loading one)

Also, for formatting, all you have to do is copy+paste it in these: " ``` "

3 Likes

Pretty much what @posatta said.


You dont need to do
local idle = game.Workspace:FindFirstChild(game.Players.LocalPlayer.Name).Humanoid:LoadAnimation(script.Hold)

Just do
idle:Stop() under the Unequipped connection.

1 Like

I see…
Sorry, thought the idle variable was outside the Equipped connection.

1 Like

Whoops, that’s actually a good idea. If he moves the LoadAnimations outside of the connections and removes them from all the connections, then he could just call idle:Play for Equipped and idle:Stop for Unequipped like you said.

2 Likes