Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

attempt to index nil with "head"?

Asked by 2 years ago
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?

2 answers

Log in to vote
2
Answered by
Rare_tendo 3000 Moderation Voter Community Moderator
2 years ago

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:

  • Removing every time they respawn:

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)
  • Removing the sounds once: when they initially spawn in

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)
Ad
Log in to vote
0
Answered by
bailley5 114
2 years ago

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)

Answer this question