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

Attempt to index nil with waitforchild on a npc?

Attempt to index nil with waitforchild on a npc and this is a reward script here's my code

local Player = game.Players.LocalPlayer
local Leaderstat = Player:WaitForChild("leaderstats")
local Humanoid = script.Parent.Humanoid
function Dead() 
	Player.leaderstats.Cash.Value = Player.leaderstats.Cash.Value + 100
wait(0.1) 
script:remove()
end 
Humanoid.Died:connect(Dead) 

2 comments

0

On which line does it occur?? And also, is this a local or server script?

0

a server script and on the leaderstat part

1 answer

✓ Accepted answer

You said this was a server script, okay. So the problem is, you can't do game.Players.LocalPlayer on a server script. A workaround around this is the .PlayerAdded event, wich returns the player as an argument. Here is your script rewritten:

game.Players.PlayerAdded:Connect(function(player) -- this will be player instead of using LocalPlayer
	
	local Leaderstats = player:WaitForChild("leaderstats")
	local Humanoid = script.Parent.Humanoid
	
	function Dead()
		
		Leaderstats.Cash.Value += 100 -- made some changes so its simpler
		wait(0.1) 
		script:Destroy()
		
	end 
	
	Humanoid.Died:Connect(Dead) 
	
end)

4 comments

0

:0 it worked! thank you!

0

Oh wait it only worked once

0

and also it says dead is a global consider changing it to local

0

I only worked once because you destroy the script duh

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