Playing an animation when a tool is equipped, yet returns an infinite yield when trying to stop animation whenever I unequip the tool

  1. What do you want to achieve?
    I want to achieve learning how to successfully stop a looped animation whenever I unequipped a tool.

  2. What is the issue?
    Equipping is fine, but when I unequip the tool, it returns an infinite yield. It looks like it’s trying to find (“Humanoid”) in Backpack. I also can’t tell if my script works at all which is weird since both of my functions are nearly identical. I’ll list it below.

  3. What solutions have you tried so far?
    I tried using FindFirstChild() instead of WaitForChild since I checked the API reference. It fixed it finding Humanoid at first but couldn’t find the animation. I also noticed that the parent of tool is Backpack but I have no idea how to fix it.

local tool = script.Parent
local players = game:GetService("Players")

local function onEquipped()
	local character = tool.Parent
	local humanoid = character:WaitForChild("Humanoid")
	local animation = humanoid:LoadAnimation(tool:WaitForChild("Animation"))
	animation.Looped = true 
	animation:Play()
	local player = players:GetPlayerFromCharacter(character)
	print("Started")
end

local function onUnEquipped()
	local character = tool.Parent
	local player = players:GetPlayerFromCharacter(character)
	print("character is fine")
	local humanoid = character:WaitForChild("Humanoid")
	print("humanoid is fine")
	local animation = humanoid:LoadAnimation(tool:WaitForChild("Animation"))
	print("animation is fine")
	if animation.IsPlaying ==  true then
		animation:Stop()
		print("Ended")
	end
end

Thank you for reading I appreciate it :slight_smile:

Try doing


local function onUnEquipped()
-	local character = tool.Parent
+ local player = tool.Parent.Parent
+local character = player.Character
1 Like

Once you unnequip a tool, the parent of the tool is no longer the character, it’s the backpack. That is why it is yielding because Humanoid doesn’t exist there.

1 Like

Ahh, yeah. I suspected it was something related to that. Thank you!!

!! It works for fixing the Humanoid problem. Although to stop the animation doesn’t work but it’s fine, just a few tweaks. Tysm!

That’s because you’re loading an entirely new animation track instance.