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)
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
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!