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

Script return "attempt to index a nil value" after every death?

Hi guys. This walk script for a Zombie keeps returning the following error right after it's death. It annoys me because nothing is wrong with the code.

20:18:30.178 - Workspace.Lightning Zombie.walk:33: attempt to index a nil value 20:18:30.181 - Stack Begin 20:18:30.182 - Script 'Workspace.Lightning Zombie.walk', Line 33 20:18:30.183 - Stack End

local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
local torso = script.Parent:FindFirstChild("Torso")
function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = false
	local dist = 1000
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("Right Arm")
			human = temp2:findFirstChild("Humanoid")
			Zombie = temp2:FindFirstChild("Zombie")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) and Zombie == nil then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end




while torso ~= nil do
	wait()
	local target = findNearestTorso(script.Parent:FindFirstChild("Torso").Position) --Problem Here
	if target ~= false and target ~= nil then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end
end

2 comments

0

That happened to me with my AI. I just ignore it.

0

"Give up" is not a useful answer.

1 answer

✓ Accepted answer

You've already defined torso on line 3, so use that instead of writing script.Parent:FindFirstChild("Torso") again on line 33.

The problem is that the while loop doesn't stop because the torso doesn't stop existing The torso just has no Parent. Since you're looking for it again on line 33 and assuming it exists since you then try to get its Position, you're trying to get the Position of nothing because Torso isn't here anymore, so what you can do is write while torso.Parent do to correct the while loop, and move the wait() to the bottom of the loop so it doesn't give it time for something to change.

1 comment

0

I like your answer. However, I have not yet marked it correct because I haven't tested yet. Thanks anyway!

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