Gun script just stops working after respawning

I made a gun script that plays animations upon shooting, reloading etc, but whenever the player respawns, there is either an error for the script saying LoadAnimation() requires the humanoid object to be a descendant of the game object or there is no error but the gun doesn’t work. Please help as I have tried a lot of things to fix this issue but it wouldn’t work.

Part where I get the error:

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()

while char == nil do
	char.AncestryChanged:wait()
end

local humanoid = char:WaitForChild("Humanoid")
local reloadAnimation = humanoid:LoadAnimation(reloadAnim)
local shootAnimation = humanoid:LoadAnimation(shootAnim)
local emptytrack = humanoid:LoadAnimation(emptyAnim)

Is the script running every time a new character is created or just in PlayerScripts?

It is inside a tool in starter pack

Change this to

if char.Parent == nil then
    char:GetPropertyChangedSignal("Parent"):Wait()
end

Because char is defined as

player.Character or player.CharacterAdded:Wait()

It will never be nil, what your code was originally checking for, however, it’s Parent could be nil.

It still does the same thing, but doesn’t give an error

This is in studio and in game

The gun script doesn’t function anymore when in game

That’s odd. Can you send the code you currently have?