How to stop an animation after Unequipping an tool?

So i’ve been trying to make an animated tool, When i equip it it works just fine, The animation plays. But when i unequip it, There is no humanoid to stop the animation.
Any help will be appriciated!

1 Like

The animation script should be a local script, how is there no humanoid? You have the player and The character.

Well, it is a local script. But the problem is that when it’s unequipped, It’s no longer in the character and it won’t detect the humanoid.

Since it’s a local script…

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait() 
local humanoid = character:WaitForChild("Humanoid")

From local scripts, you can easily define the player and get his character which has the humanoid inside…

You can store the animation you want to play in a variable somewhere on top. Then you can add this line when the tool is unequipped.

local anim

-- somewhere in the code
if anim then

How would that work?
If i may get an explenaition, I also should’ve sent a image of the current script that i have. So here you go!

This is how the script looks so far.

Change the way you get the humanoid.

before you do the function at the start of the script, define your variables

local Player = game.Players.LocalPlayer
local Character = Player.Character
local Humanoid = Character:WaitForChild("Humanoid")

then just remove the humanoid variables inside the functions

You need a direct reference to the Animation Track loaded by the Animator to stop the Animation. Loading the same animation and stopping it won’t do anything since the original Animation is still playing.

The way I made this is doing a repeat loop and check if the tool’s parent is still Player’s Char.

    local Animator = Humanoid:FindFirstChild("Animator")
    local PlayAnim = Animator:LoadAnimation(Animation)
    coroutine.wrap(function) --so it don't yield
        repeat task.wait() until script.Parent.Parent ~= Player.Character

Oh, Thanks! This worked out for me!
Thanks to everybody that wanted to help me, i really appriciate it!

I wouldn’t recommend this approach when you can just use the tool’s ‘Unequipped’ event/signal instead.

local Script = script
local Tool = Script.Parent

local Animation = nil --Reference to 'Animation' object.
local Track = nil --'Track' upvalue.

local function OnEquipped()
	if not Track then --Don't need to set 'Track' multiple times.
		local Character = Tool.Parent
		if not Character then return end
		local Humanoid = Character:FindFirstChildOfClass("Humanoid")
		if not Humanoid then return end
		local Animator = Humanoid:FindFirstChildOfClass("Animator")
		if not Animator then return end
		Track = Animator:LoadAnimation(Animation)

local function OnUnequipped()
	if Track then Track:Stop() end

1 Like