Edited the script, yet again there seems to be a problem with the for loop that Destroys the hats in the player (the second for loop)...
The second loop which destroys the hats of the player works fine in Roblox Studio but not in game.
player = game:GetService("Players").LocalPlayer player.CharacterAdded:connect(function(character) for i,v in pairs(game.StarterPlayer:GetChildren()) do if v.ClassName == "Hat" and v.Name == game.StarterPlayer.HatSave.Value then v.Parent = player.Character end end wait(3) for i,v in pairs(character:GetChildren()) do if v.ClassName == "Hat" and v.Name ~= game.StarterPlayer.HatSave.Value then v:Destroy() end end end)
It is possible that the hats have not loaded yet and are loading after you try to remove them. In that case, you could just add a short delay before removing the hats.
You're also using CharacterAdded
from a LocalScript, which won't work because the character loads before the script. Instead, just use character=player.Character
or character=player.Character or player.CharacterAdded:wait()
You shouldn't to use the CharacterAdded
event in a LocalScript
, given that they automatically reload along with the character...(when in the right services (PlayerGui..)).
local player = game.Players.LocalPlayer local character = player.Character if not (character or character.Parent) then character = player.CharacterAdded:wait() end wait(1) -- slight delay, in case the hats take time to load for _, child in pairs(character:GetChildren()) do if child:IsA("Hat") or child:IsA("Accoutrement") then child:Destroy() end end for _, child in pairs(playerGui:GetChildren()) do if child:IsA("Hat") then v.Parent = character end end
I'd recommend -- storing the hats in "ServerStorage", and cloning them to the character whenever they spawned instead of keeping them locally.
Pretty much works on the same logic, but makes use of the CharacterAdded
and PlayerAdded
events.
local function Refreshed(player) local character = player.Character local service = game.ServerStorage for _, child in pairs(character:GetChildren()) do if child:IsA("Hat") or child:IsA("Accoutrement") then child:Destroy() end end for _, child in pairs(service:GetChildren()) do if child:IsA("Hat") or child:IsA("Accoutrement") then v.Parent = character end end end game.Players.PlayerAdded:connect(function(player) player.Changed:connect(function(property) if (property == "Character") then wait(1) -- slight delay, in case the hats take time to load Refreshed(player) end end) end)