Hat giver script works 90 percent of the time, how to make it 100?

So I have this hat giver script that works very well, but sometimes it just doesn’t work, which is rare, any way to make it work all the time?

game.Players.PlayerAdded:connect(function(player)
	player.CharacterAdded:connect(function(character)
		if player:WaitForChild("leaderstats").Hats.Value == 1 then -- Afro
			wait(1)
			local d = character:GetChildren()
			for i=1, #d do
				if (d[i].className == "Accessory") then
					d[i]:remove()
				end
			end
			if character:findFirstChild("Humanoid") ~= nil then -- Accessory script
				local h = Instance.new("Accessory")
				local p = Instance.new("Part")
				h.Name = "Hat"
				p.Parent = h
				p.Position = character:findFirstChild("Head").Position
				p.Name = "Handle"
				p.BrickColor = BrickColor.new("Really black") 
				p.formFactor = 0
				p.Size = Vector3.new(-0,-0,-1)
				p.BottomSurface = 0
				p.TopSurface = 0
				p.Locked = true
				script.AfroMesh:Clone().Parent = p
				h.Parent = character
				print("It should work")
				h.AttachmentPos = Vector3.new(0, -0.20, 0)
				wait(.1)
			end
		end --Skipped over people without value
	end)
end)
2 Likes

There’s an alternative listener called CharacterAppearanceLoaded. Replace that with CharacterAdded. It is suggested to use that listener over the other for hats and accessories.

3 Likes

Yeah. It’s cases like this that cause me to rant against using outdated free model code or handle welding operations at run time. I’d have your assets ready made in the game under ServerStorage, to which you simply clone and configure as necessary when the server loads up.

For a game I work on, I have accessories and then a part named Handle that represents the root of the asset to add to the character’s appearance. There’s an attachment under that Handle that’s equivalent to the name of an attachment in the character - for hair, its HairAttachment. These attachments get lined up so I position the attachment or handle so it’ll fit onto a rig properly.

Once this is all done, I simply call Humanoid:AddAccessory(Accessory) and we’re done.

1 Like