Animation not destroying when unequipped

My goal: When the tool is unequipped it will run the function so the animations the tool uses (swordwalk/swordidle) will stop and the default characters animations will play. I sort of works but reupdates when the player starts running.

I think this is something to do with the Humanoid.Running function I used in EquippedAnimations function.

code:

local player = game.Players.LocalPlayer
local Character = player.Character or player.PlayerAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

local Sword_Walk_Animation = Instance.new("Animation")
Sword_Walk_Animation.AnimationId = "rbxassetid://9404399317"
local AnimationTrackWalk = Humanoid.Animator:LoadAnimation(Sword_Walk_Animation)

local Sword_Idle_Animation = Instance.new("Animation")
Sword_Idle_Animation.AnimationId = "rbxassetid://9404394687"
local AnimationTrackIdle = Humanoid.Animator:LoadAnimation(Sword_Idle_Animation)

local Sword_Equip_Animation = Instance.new("Animation")
Sword_Equip_Animation.AnimationId = "rbxassetid://9537941896"
local AnimationTrackEquip = Humanoid:LoadAnimation(Sword_Equip_Animation)

local shouldPlay = false	

local function EquippedAnimations()
	if tool.Equipped then
		Sounds.Unsheath:Play()
		AnimationTrackEquip:Play()
				shouldPlay = true
				while shouldPlay do
					wait()
					Humanoid.Running:Connect(function(speed)
						if speed > 0 then
					AnimationTrackWalk:Play()
					AnimationTrackIdle:Stop()
						else
					AnimationTrackWalk:Stop()
					AnimationTrackIdle:Play()
				end
					end)
				end
			end
		end

local function Unequipped()
		tool.Unequipped:Connect(function()
		shouldPlay = false
		print("sttoped")
		AnimationTrackIdle:Stop()
		Sword_Idle_Animation:Destroy()
		AnimationTrackWalk:Stop()
		Sword_Walk_Animation:Destroy()
	end)
	end

		
tool.Equipped:Connect(EquippedAnimations)
tool.Unequipped:Connect(Unequipped)
tool.Activated:Connect(slash)
tool.Handle.Touched:Connect(onTouch)

Another related post to mine is: Tool idle and walk animations won’t stop when unequipped - #2 by Temeraire149
though it had no solution and was a year ago.

Well if Humanoid.Running is the case, then disconnect the function when unequiping.

Also why do you have player.PlayerAdded:Wait() for character? I believe it should be player.CharacterAdded:Wait()

Could you show an example for doing that?

Well you could break the function by returning.
Example Code

local tool = script.Parent
local player = game.Players.LocalPlayer
local Character = player.Character or player.CharacterAdded:Wait()
local Humanoid = player.Character:WaitForChild("Humanoid")	

local function EquippedAnimations()
	Humanoid.Running:Connect(function(speed)
		if tool.Parent == player.Backpack then return end
		if speed > 0 then
			print(1)
		else
			print(2)
		end
	end)
end

tool.Equipped:Connect(EquippedAnimations)

If the tool is in the Backpack, then that means the tool is unequipped.

1 Like