Animations on tool not working as intended

Hello, I made custom idle and walk animations which should play while having a tool equipped but are stopped when the tool is unequipped. However, there are a few issues I’m having:

  • Walking animation frequently continues playing even while character is standing still.
  • Animations continue playing even when tool is unequipped.
  • Animations are animated differently from what they were intended (e.g. weird arm rotations).

I’ve tried looking into this in the Devforum and creator documentation and tried changing the animation priority. However, I haven’t been able to find any solution and changing the priority has done little to no help in solving the problem.

Here is the code (It is running on a local script) :

local BlastBomb = script.Parent

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local Animations = BlastBomb:WaitForChild("Animations")

local IdleAnimation = Animations:WaitForChild("Idle")
local WalkAnimation = Animations:WaitForChild("Walk")

local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()

local Humanoid = Character:WaitForChild("Humanoid")
local Animator = Humanoid:WaitForChild("Animator")

local LoadedAnim

function onEquip()
	local Connection

	LoadedAnim = Animator:LoadAnimation(IdleAnimation)

	LoadedAnim.Priority = Enum.AnimationPriority.Idle
	LoadedAnim.Name = "Idle"
	LoadedAnim.Looped = true
	LoadedAnim:Play()
	
	Connection = Humanoid.Running:Connect(function(Speed)
		if Speed > 0 then
			if LoadedAnim then
				if LoadedAnim.Name ~= "Walk" then
					LoadedAnim:Stop()
				end
			end	
			LoadedAnim = Animator:LoadAnimation(WalkAnimation)

			LoadedAnim.Priority = Enum.AnimationPriority.Movement
			LoadedAnim.Name = "Walk"
			LoadedAnim.Looped = true
			LoadedAnim:Play()
		elseif Speed == 0 then
			if LoadedAnim  then
				if LoadedAnim.Name ~= "Idle" then
					LoadedAnim:Stop()
				end
			end
			
			LoadedAnim = Animator:LoadAnimation(IdleAnimation)

			LoadedAnim.Priority = Enum.AnimationPriority.Idle
			LoadedAnim.Name = "Idle"
			LoadedAnim.Looped = true
			LoadedAnim:Play()
		end
	end)
	
	while true do
		if not BlastBomb:IsDescendantOf(Character) then
			Connection:Disconnect()
			
			if LoadedAnim then
				LoadedAnim:Stop()
			end
			
			break
		end
		
		RunService.RenderStepped:Wait()
	end
end

function onUnEquip()
	if LoadedAnim then
		LoadedAnim:Stop()
		LoadedAnim.Looped = false
		LoadedAnim = nil
	end
end

BlastBomb.Equipped:Connect(onEquip)
BlastBomb.Unequipped:Connect(onUnEquip)