Script doesn't stop animation when unequipped

As you’ve seen in the title, the following script I have does not work and I am unable to locate the source and reason why it wont work.

local track
local holdanimation

local function toolEquipped()
	tool.Handle.Equip:Play()
	holdanimation = script.Parent.Parent.Humanoid:LoadAnimation(hoLdinggun)
	holdanimation:Play()
end

local function toolunequipped()
	if track and holdanimation then
		track:Stop()
		holdanimation:Stop()
	end
end

tool.Equipped:Connect(toolEquipped)
tool.Unequipped:Connect(toolunequipped)

local mouse = plr:GetMouse()

mouse.Button1Down:Connect(function()
	held = true
	track = script.Parent.Parent.Humanoid:LoadAnimation(animation)
	track.Priority = Enum.AnimationPriority.Action
	track:Play()
end)

mouse.Button1Up:Connect(function()
	held = false
	track:Stop()
end)

It always gives me this error
image
When unequipped

It will also give me this error,
image

Well the unequipped function doesn’t prevent the mouse button from clicking, and I’m not sure why you use mouse.Button1Down/Up instead of tool.Activated/Deactivated, since this will likely solve one of the errors.

1 Like

cant you just load already the animations on the vars?

cuz everytime the tool equipped event fires
the var holdanimation will be updated to new loaded animation track
so you cant access anymore the previous track on that var to stop it

also you shouldn’t load a lot of same animations
you cannot exceed more than 256 tracks or you will get an error when you reach it

local track = script.Parent.Parent.Humanoid:LoadAnimation(animation)
track.Priority = Enum.AnimationPriority.Action

local holdanimation = script.Parent.Parent.Humanoid:LoadAnimation(hoLdinggun)

local function toolEquipped()
	tool.Handle.Equip:Play()
	holdanimation:Play()
end

local function toolunequipped()
	track:Stop()
	holdanimation:Stop()
end

tool.Equipped:Connect(toolEquipped)
tool.Unequipped:Connect(toolunequipped)

local mouse = plr:GetMouse()

mouse.Button1Down:Connect(function()
	held = true
	track:Play()
end)

mouse.Button1Up:Connect(function()
	held = false
	track:Stop()
end)
2 Likes