game.Players.PlayerAdded:connect(function(p) for i,v in pairs(p.Character.Head:children()) do if v:IsA'Sound' then v:destroy'' end end end)
Can someone help me?
Attempt to index nil with Head
generally means the object you're attempting to index "Head" with, meaning you're trying to access the Head object in another object, is nil. This means that p.Character
is nil. This can happen because the event fires immediately when the player joins and their character hasn't loaded yet.
The problem with this post is that you haven't explained what you're trying to achieve. We can infer that you're either trying to remove any sound instances in the player's head only once, when they initially join and their character is loaded, or you're trying to remove them every time they respawn; The issue is we don't know which one you're trying to achieve, which is why it's always best to explain what you intend the code to do and what it's doing instead, which helps to avoid the XY Problem. I'm going to assume you want to treat both cases here:
This can be done using a CharacterAdded event in conjunction with the PlayerAdded event:
game.Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(character) for _, v in ipairs(character:WaitForChild("Head"):GetChildren()) do if v:IsA("Sound") then v:Destroy() end end end) end)
CharacterAdded will be used again, but instead, using the :Wait
function. :Wait
on a signal will yield (pause) the script until the event fires and it will return the newly spawned character:
game.Players.PlayerAdded:Connect(function(player) local character = player.Character or player.CharacterAdded:Wait() for _, v in ipairs(character:WaitForChild("Head"):GetChildren()) do if v:IsA("Sound") then v:Destroy() end end end)
You made a lot of errors and mistakes, I fixed it up it should work fine now.
game.Players.PlayerAdded:connect(function(p) for i,v in pairs(p.Character.Head:GetChildren()) do if v:IsA('Sound') then v:Destroy() end end end)