After respawning, equipping a tool doesn't play animation

I’m scripting a tool that plays an animation on the player’s character when equipped. The tool is located in StarterPack and the animation is played through a LocalScript:

local tool = script.Parent
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()

while char.Parent ~= game.Workspace do
    char = plr.Character.AncestryChanged:Wait()
end

local hum = char:WaitForChild("Humanoid")

local playAnim = hum:LoadAnimation(tool.Animation)

tool.Equipped:Connect(function()    
    playAnim:Play()
end)

tool.Unequipped:Connect(function()
    playAnim:Stop()
end)

The animation plays as intended when you first join the game, but if I reset and try to equip the tool again, it doesn’t play.

I’ve tried to incorporate obvious solutions such as doing Player.Character.AncestryChanged:Wait() before defining the Humanoid and defining the character as Player.CharacterAdded:Wait() alongside Player.Character. I also looked at this thread for help, but to no avail: Getting error "LoadAnimation requires the Humanoid object to be a descendant of the game object" despite waiting for Character

Something interesting I was able to observe was that the character’s Parent is set to workspace when you first join the game, but is set to nil any time after you respawn in the same session. So it is clear that using AncestryChanged:Wait() is not helping. I’ve exhausted every possible solution, so is there anything I can do to fix this?

4 Likes

Just assign the Humanoid from within the Equipped event.

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

local character
local humanoid
local playAnimation

tool.Equipped:Connect(function ()
    character = character or tool.Parent or player.Character or player.CharacterAdded:Wait()
    humanoid = humanoid or character:WaitForChild("Humanoid")

    if not playAnim then
        playAnim = humanoid:LoadAnimation(playAnim)
    end

    playAnim:Play()
end)

tool.Unequipped:Connect(function ()
    playAnim:Stop()
end)

Using AncestryChanged is unnecessary. As for respawning behaviour, this is normal. A character is constructed, put in the workspace and assigned to Player.Character when a character respawns. If it dies and LoadCharacter is called, then the previous character is removed and the cycle repeats itself of creating a new character model.

18 Likes

Thank you! I’ll be sure to remember this :slight_smile:

1 Like