Tool animation playing after the tool is removed?

I have a script that plays the tool idle animation when equipped, and stops it when unequipped.

local player = game.Players.LocalPlayer


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

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

animation.AnimationId = "http://www.roblox.com/asset/?id=6716230447"
local animtrack = humanoid:LoadAnimation(animation)

script.Parent.Equipped:connect(function()
	animtrack:Play()
end)

script.Parent.Unequipped:connect(function()
	animtrack:Stop()
end)

How would I detect when the tool is destroyed and stop the animation?

4 Likes

Here’s a pseudo-destroyed event you could use:

script.Parent.AncestryChanged:connect(function()
    if not script.Parent:IsDescendantOf(game) then
        animtrack:Stop()
    end
end)

EDIT: The above code doesn’t work use:

1 Like

I’ve heard that when a tool is destroyed it stops all the scripts inside it from working but I’m not too sure if that’s true. I’ll try this in a minute and let you know if it works!

The unequip event doesn’t know that the animation is playing so you gotta do

script.Parent.Unequipped:connect(function()
    animtrack:Play()
	animtrack:Stop()
end)
1 Like

I just tested this and it doesn’t work. That’s a mistake on my part. Here’s a working solution:

game.DescendantRemoving:Connect(function(obj)
	if obj == script.Parent then
		print("DESTROYED")
	end
end)
2 Likes

I tested this script and now it works! Thank you very much!

2 Likes

you also can try checking if the animation is playing like:

local player = game.Players.LocalPlayer
local playing = false

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

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

animation.AnimationId = "http://www.roblox.com/asset/?id=6716230447"
local animtrack = humanoid:LoadAnimation(animation)

script.Parent.Equipped:connect(function()
	if playing == false then
		playing = true
			animtrack:Play()
	end
end)

script.Parent.Unequipped:connect(function()
	if playing == true then
		playing = false
			animtrack:Stop()
	end
end)
2 Likes

Where exactly do you place this code?