My "keep hats on death" script is not working, why wouldn't it work?

I Have used some of the help i got on the forum to make a script that hats will remain on the character once the character dies.
For some reason the script wouldn’t work, I have tried several things like changing the script’s position but nothing really worked.
The script:

local savedAccessories = {}
local player = game.Players:GetPlayerFromCharacter(script.Parent)
local char = script.Parent
local Humanoid = char:FindFirstChild("Humanoid")
local head = script.Parent.Head 
player.CharacterAppearanceLoaded:Connect(function()
	for _, part in ipairs(char:GetDescendants()) do
		if part:IsA("Accessory") then
			local handle = part.Handle
			local weld = part:FindFirstChildOfClass("Weld")
			local parent = head
			local cf = parent.CFrame:inverse() * handle.CFrame
			savedAccessories[#savedAccessories + 1] = {Handle = handle; Parent = parent; Offset = cf}
		end
	end
end)

Humanoid.Died:Connect(function()
	for _, accessoryData in ipairs(savedAccessories) do
		local weld = Instance.new("Weld")
		weld.Part0 = accessoryData.Parent
		weld.Part1 = accessoryData.Handle
		weld.C0 = accessoryData.Offset
		weld.Parent = accessoryData.Parent
		print("Succssesfully welded hats")
	end
end)

(the script is located in starter character)

I don’t know if this will help, but I also tried making something similar,

I came to an conclusion that accessories (Hats), for some reason, just ignore old welds and new welds after death, instead of using welds, I used HingeConstraints, setting the rotation limits to 0, so the hats don’t rotate. Setting one attachment to the HatAttachment in the accessory, and one attachment is set to a attachment which is on the body.

You can disable Humanoid.BreakJointsOnDeath when the humanoid dieds. The existing welds and motor6ds are still destroyed, but your new welds won’t be.

Humanoid.Died:Connect(function()
	Humanoid.BreakJointsOnDeath = false
	for _, accessoryData in ipairs(savedAccessories) do