Attempt to index nil with 'Character'

I wanna make a basic A.I. for this bad zombie game (on purpose).
But it always throws the error in the title.
Mind you help?
This is a serverscript inside the model of the zombie (it is all unanchored)

local Players = game:GetService("Players")

local part = script.Parent:FindFirstChild('HumanoidRootPart') or script.Parent:FindFirstChildWhichIsA('Humanoid').RootPart

local maxDistance = 100

local getNearestPlayer = function()
	local nearestPlayer, nearestDistance
	for _, player in pairs(Players:GetPlayers()) do
		if (player) then
			local distance = player:DistanceFromCharacter(part.Position)
			if not player.Character or 
				distance > maxDistance or
				(nearestDistance and distance >= nearestDistance)
			then
				continue
			end
			nearestDistance = distance
			nearestPlayer = player
		end
	end
	return nearestPlayer
end

local loop = coroutine.create(function()
	while true do
		task.wait(3)
		local player = getNearestPlayer()
		local walkToPart = player.Character:FindFirstChild('HumanoidRootPart') or player.Character:FindFirstChildWhichIsA('Humanoid').RootPart
		script.Parent:FindFirstChildWhichIsA('Humanoid'):MoveTo(walkToPart.Position, walkToPart)
		script.Parent:FindFirstChild('HumanoidRootPart'):SetNetworkOwner(nil)
	end
end)

coroutine.resume(loop)

script.Parent:FindFirstChildWhichIsA('Humanoid').Died:Connect(function()
	coroutine.close(loop)
end)

game:GetService('ReplicatedStorage'):FindFirstChild('MapStarted').Changed:Connect(function(v)
	if (game:GetService('ReplicatedStorage'):FindFirstChild('MapStarted').Value == false) then
		coroutine.close(loop)
	end
end)

The error message should include a line where the error is occurring. Could you please send which line the errors occurs in, or just send the entire error message from the console?

Happens on the local walktToPart line where I define Character. (The entire error is the title)

Ahh okay, so your problem is simply that sometimes your getNearestPlayer function is returning nil. This is because you are iterating through the players, but when the game first loads there are no players, so your loop starting at for _, player in pairs(Players:GetPlayers()) do doesn’t run. You could simply check in your while loop to assure the existence of player, like so:

local loop = coroutine.create(function()
	while true do
		task.wait(3)
		local player = getNearestPlayer()
		if player then
			local walkToPart = player.Character:FindFirstChild('HumanoidRootPart') or player.Character:FindFirstChildWhichIsA('Humanoid').RootPart
			script.Parent:FindFirstChildWhichIsA('Humanoid'):MoveTo(walkToPart.Position, walkToPart)
			script.Parent:FindFirstChild('HumanoidRootPart'):SetNetworkOwner(nil)
		end
	end
end)
1 Like

Thanks! God I feel so stupid for not doing that :skull:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.