I have this idle animation equipped in a tool, which plays the idle when equipped, then if I press W stops and when I release W plays again. But when I am pressing W and unequip the tool at the same time the animation keeps playing. I've tried adding some stuff but nothing is working so I turned to this

local player = game.Players.LocalPlayer

repeat wait(1) until player.Character

local character = player.Character
local humanoid = character:WaitForChild("Humanoid")

local userInput = game:GetService("UserInputService")

local animation = Instance.new("Animation")
animation.Name = "Idle"
animation.Parent = script.Parent

local animation2 = Instance.new("Animation")
animation2.Name = "Equip"
animation2.Parent = script.Parent


animation.AnimationId = "rbxassetid://5188207897"  
local animtrack = humanoid:LoadAnimation(animation)

animation2.AnimationId = "rbxassetid://5188248725"  --5188248725
local animtrack2 = humanoid:LoadAnimation(animation2)
animtrack2.Priority = Enum.AnimationPriority.Action
local tool = script.Parent

script.Parent.Equipped:connect(function()
	animtrack2:Play()
	script.Parent.Sound:Play()
end)
wait(.26)
script.Parent.Equipped:connect(function()
	animtrack:Play()
	
	userInput.InputBegan:Connect(function(input)
	
		 if input.KeyCode == Enum.KeyCode.W  then
			
		animtrack:Stop()
	end
end)

userInput.InputEnded:Connect(function(input)	
		 if input.KeyCode == Enum.KeyCode.W then
			animtrack:Play()
		elseif tool.Unequipped == true and input.KeyCode == Enum.KeyCode.W then
			animtrack:Stop()
			
	end
end)

	
	
end)

script.Parent.Unequipped:connect(function()
	animtrack:Stop()
	
	userInput.InputEnded:Connect(function(input)	
		 if input.KeyCode == Enum.KeyCode.W then
			
			animtrack:Stop()
		end
		end)
end)