Animation works when Reequipped

My animation works properly only when it is reequipped, after that everything works good. I have tried to identify the cause of this problem but have not yet managed. What are your thoughts?

local Players = game:GetService("Players")
local Player = Players.LocalPlayer

local Tool = script.Parent

Tool.Activated:Connect(function()
	local Character = Player.Character
	local Humanoid = Character:FindFirstChild("Humanoid")
	local Animation = Humanoid:FindFirstChild("YoYoAnimation")

	local YoYoAnimation = Humanoid:LoadAnimation(Animation)
	
	YoYoAnimation:Play()

	wait(2)

	YoYoAnimation:Stop()
end)

This function is deprecated. Use Animator:LoadAnimation. To get the Animator for a player, it is located under the humanoid.

Humanoid:LoadAnimation should still work, though I’d recommend using Animator:LoadAnimation.

I’m not sure what the problem is, but try this code instead:

local Players = game:GetService("Players")
local Player = Players.LocalPlayer

local Tool = script.Parent

local YoYoAnimationTrack

Tool.Equipped:Connect(function()
	local Character = Player.Character
	if not Character then return end
	local Humanoid = Character:FindFirstChild("Humanoid")
	if not Humanoid then return end
	local Animation = Humanoid:WaitForChild("YoYoAnimation", 1) --Maybe try putting the Animation inside the tool. The problem might be that you add the animation at the wrong time.
	if not Animation then return end

	if YoYoAnimationTrack then
		YoYoAnimationTrack:Destroy()
	end
	YoYoAnimationTrack = Humanoid:LoadAnimation(Animation)
end)

Tool.Activated:Connect(function()
	YoYoAnimationTrack:Play()

	local didUnequip = false
	local unequipConnection = Toop.Unequipped:Connect(function()
		didUnequip = true
	end)

	YoYoAnimationTrack.Completed:Wait()

	if not didUnequip then
		YoYoAnimation:Stop()
	end
	unequipConnection:Disconnect()
end)