The character doesn't load instantly, you will need another function to fire when the character is added, doing this also allows you to have them removed each time a player dies. The game.Players.PlayerAdded function is unnecessary as each time any player joins it will try to remove the player's hats. Here's the code you should be using assuming this is a local script:
1 | local player = game.Players.LocalPlayer |
3 | player.CharacterAdded:connect( function (char) |
4 | for _,obj in pairs (char:GetChildren()) do |
Instead of having this, you could use a server script in Workspace or ServerScriptService, here's the script you could use for that:
1 | game.Players.PlayerAdded:connect( function (player) |
2 | player.CharacterAdded:connect( function (char) |
3 | for _,obj in pairs (char:GetChildren()) do |
If this worked for you and/or helped you please vote up and accept this as the answer!