Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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)

3 comments

0

make sure its in a localscript. server doesn't have a localplayer because it's not a player, its a host

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

0

doggy's answer is good too

2 answers

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

1 comment

0

I'm still getting the same problem

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.