:Stop() doesn't stop the animation

When I equip the animation, it works fine but when I unequip it the animation doesn’t stop.

Local script in tool

local crate = script.Parent

crate.Equipped:Connect(function()
	crate.OnEquip:FireServer(true)
end)

crate.Unequipped:Connect(function()
	crate.OnEquip:FireServer(false)
end)

Server script in tool

local crate = script.Parent
local animation = crate:WaitForChild("Carrying")

crate.OnEquip.OnServerEvent:Connect(function(player, equipped)
	local character = player.Character
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if humanoid then
		local animator = humanoid:FindFirstChildOfClass("Animator")
		if animator then
			local animationTrack = animator:LoadAnimation(animation)
			if equipped then
				animationTrack:Play()
			else
				animationTrack:Stop()
			end
		end
	end
end)

I would say the problem is caused by creating a new animationtrack variable on every call.
When you call it the first time to run the animation the function creates a local variable (local animationTrack) but when you call it the second time to stop the animation it creates another local variable and setting the state to :Stop() instead of stopping the variable from the first call.
so:
—> Call function
Creates local variable named animationTrack and set it to Play()
–>> Call function
Creates local variable named animationTrack and set it to Stop()

Your not actually telling it to stop the animationTrack variable from the first call.

Alright so um, how do I fix it? Should I just use two remote events?

Try this, I haven’t tested it though:

local crate = script.Parent
local animation = crate:WaitForChild("Carrying")
local animationTrack=nil

crate.OnEquip.OnServerEvent:Connect(function(player, equipped)
	local character = player.Character
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if humanoid then
		local animator = humanoid:FindFirstChildOfClass("Animator")
		if animator then
			if not animationTrack then animationTrack = animator:LoadAnimation(animation) end
			if equipped then
				animationTrack:Play()
			else
				animationTrack:Stop()
			end
		end
	end
end)
1 Like