I'm trying to remove a players hat then give them a new hat. Removal script:
function newPlayer(player) wait(1) p = player.Character:GetChildren() for i=1, #p do if p[i].className == "Hat" then p[i]:Remove() end end end game.Players.ChildAdded:connect(newPlayer)
Giving script:
game.Players.PlayerAdded:connect(function(player) repeat wait()until player.Character local hatId=1045408 local hat = game:service("InsertService"):LoadAsset(hatId):GetChildren()[1] hat.Parent=player.Character end)
All I want to know is how to combine them into one script and make it more efficient; and work.
local HatIDs = {1045408} local Hats = {} local Players = Game:GetService("Players") local InsertService = Game:GetService("InsertService") function PlayerAdded(player) local Character = player.Character or player.CharacterAdded:wait() -- waits for the character if it doesn't exist already. Delay(1, function() for index, object in pairs(Character:GetChildren()) do if object:IsA("Hat") then object:Destroy() end end for Index, Hat in ipairs(Hats) do Hat:Clone().Parent = Character end end) end for index, ID in pairs(HatIDs) do table.insert(Hats, InsertService:LoadAsset(ID):GetChildren()[1]:Clone()) end Players.PlayerAdded:connect(PlayerAdded) for index, player in pairs(Players:GetPlayers()) do PlayerAdded(player) end
HatIDs
is where the IDs for hats are stored.
Hats
is the array where the hats themselves are referenced.
Combining them into 1 function in 1 script would be very efficient instead of 2 seperate scripts with 2 different functions.
game.Players.PlayerAdded:connect(function(player) repeat wait() until player.Character --Waits for the character to exist. for i,v in pairs(player.Character:GetChildren()) do --Using in pairs will be more efficient than setting a variable for all the character's children and created a table and accessing a value's position in the table every loop. if v:IsA("Hat") then v:Destroy() --Destroy is much more efficient than Remove. end end local hatClone = game:GetService("InsertService"):LoadAsset(1045408):GetChildren()[1]:Clone() --Clone the hat in case more than 1 player joins. hatClone.Parent=player.Character end)
If I helped you out, be sure to accept my answer!