So I’m making a zombie AI out of a following NPC model I found (I don’t know if this is hated upon, but I learn from it), but when I made a wave system it stopped working, and the findNearestTorso function would always error out and return nil, here’s my code:
local Attacker = script.Parent
-- Limbs --
local Attacker_Torso = Attacker:WaitForChild('Torso')
local Attacker_Humanoid = Attacker:WaitForChild('Humanoid')
-- Settings --
local HurtDistance = 4
local HurtDamage = 20
local Cooldown = 0.5
local Canhit = true
-- Code --
function findNearestTorso(pos)
local list = workspace:GetChildren()
local torso = nil
local dist = 100000000
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("UpperTorso")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
if dist < HurtDistance and Canhit and Attacker_Humanoid.Health > 0 then
Canhit = false
-- Damaging and animating
human:TakeDamage(HurtDamage)
Attacker_Humanoid.Animator:LoadAnimation(script.Animation):Play()
-- Random sounds
local track = torso.Attachment:GetChildren()[math.random(1,#torso.Attachment:GetChildren())]
track:play()
-- Cooldown
delay(Cooldown,function()
Canhit = true
end)
end
end
end
end
end
return torso
end
while task.wait(0.15) do
local target = findNearestTorso(Attacker_Torso.Position)
if target.Parent.Name ~= Attacker.Name then
Attacker_Humanoid:MoveTo(target.Position)
end
end
I’ve improved and edited this code a lot, so I am not completely sure if my edits made it break. Any ideas? Also here’s the error if you’re wondering: