Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
1

How do I fix this "Attempt to index nil" problem?

Asked by 5 months ago

This code works just fine.

game:GetService('Players').PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        character:WaitForChild("Humanoid").Died:Connect(function()
            print(player.Name .. " has died!")
        end)
    end)
end)

But for some reason, when I define these variables below, the output tells me "Attempt to index nil with "Character."

plr = game.Players.LocalPlayer
humanoid = plr.Character:WaitForChild("Humanoid")
mouse = plr:GetMouse()

game:GetService('Players').PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        character:WaitForChild("Humanoid").Died:Connect(function()
            print(player.Name .. " has died!")
        end)
    end)
end)
0
make sure its in a localscript. server doesn't have a localplayer because it's not a player, its a host Fifkee 2017 — 5mo
0
I don't want to copy and paste my answer that feels a bit dumb but someone else had a similar problem and my answer might solve it: https://scriptinghelpers.org/questions/102870/errorhumanioid-is-not-a-valid-member-of-model 123nabilben123 472 — 5mo
0
doggy's answer is good too 123nabilben123 472 — 5mo

2 answers

Log in to vote
0
Answered by 5 months ago
Edited 5 months ago

Add the line

local Character = plr.Character or plr.CharacterAdded:Wait()

then set humanoid to Character.humanoid. When you first get the player, there's no guarantee that the character associated with that player has been added yet, so you have to wait for it

0
I'm still getting the same problem osamayousef123 14 — 5mo
Ad
Log in to vote
0
Answered by 5 months ago

Hello.

Problem

game.Players.LocalPlayer does not work on ServerScripts as ServerScripts run on a physical server instead of the client. ServerScripts also can't get the player's mouse.

Explaining the Error

Attempt to index nil with character appears when a beginner uses game.Players.LocalPlayer in a ServerScript. Attempt to index nil means you tried to index something that was nil.

The script basically thinks you're doing this:

local character = nil.Character

Fixed Code

game:GetService('Players').PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
    local humanoid = character:WaitForChild("Humanoid")

        humanoid.Died:Connect(function()
            print(player.Name .. " has died!")
        end)
    end)
end)

Please accept this answer if it helped!

Answer this question