How do I fix this error message?

Hi, I get this error message when I try run this script, there is something wrong with line 20 but I dont know what:

ServerScriptService.KillHandler:20: attempt to index nil with ‘WaitForChild’

local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local playerSaves = dataStoreService:GetDataStore("PlayerSaves")


players.PlayerAdded:Connect(function(player)
	
	local stats = Instance.new("Folder")
	stats.Name = "leaderstats"
	local kills = Instance.new("NumberValue")
	kills.Name = "Kills"
	kills.Parent = stats
	local deaths = Instance.new("NumberValue")
	deaths.Name = "Deaths"
	deaths.Parent = stats
	stats.Parent = player
	
	local function charAdded(char)
		
		local humanoid = char:WaitForChild("Humanoid")
		
		humanoid.Died:Connect(function()
			
			deaths.Value += 1
			
			local killer = humanoid:FindFirstChild("killerTag")
			
			if killer and killer.Value then
				killer.Value.leaderstats.Kills.Value += 1
			end
		end)
	end
	
	if player.Character then
		charAdded(player.Character)
	end
	
	player.CharacterAdded:Connect(charAdded())
	
	local data = playerSaves:GetAsync(player.UserId)
	
	if data then
		
		for name,value in pairs(data) do
			
			local val = stats:FindFirstChild(name)
			
			if val then
				
				val.Value = value
				
			end
			
		end
		
	end
	
end)

players.PlayerRemoving:Connect(function(player)
	
	local stats = player:FindFirstChild("leaderstats")
	
	if stats then
		
		local data = {}
		
		for _,stat in pairs(stats:GetChildren()) do
			data[stat.Name] = stat.Value
		end
		
		playerSaves:SetAsync(player.UserId,data)
		
	end
	
end)

game:BindToClose(function()
	wait(3)
end)

Attempt to index nil with WaitForChild means that you tried to use WaitForChild on something that doesn’t exist. This tells us that by the time the code runs, the character is non existent still. Another issue I’m seeing is that in this connection:

player.CharacterAdded:Connect(charAdded())

The parentheses in charAdded() execute the function, and then a value is returned if you made it return anything. You want to remove those parentheses.

2 Likes

Its working now, thank you for your help!