I made a script for an NPC where it walks from one point to another in a while loop, but if it sees a player it goes after them. I tried moving some things around to see if it works. I also get an error saying "Workspace.Guard.Script:28: attempt to index nil with 'Parent'". I need help finding out what is wrong in the script.
Script:
local firstpoint = workspace.pointforguard.Position local secondpoint = workspace.pointforguard1.Position local hum = script.Parent:WaitForChild("Humanoid") local hrp = script.Parent:WaitForChild("HumanoidRootPart") local model = script.Parent local player = game.Players.LocalPlayer local hum = script.Parent:WaitForChild("Humanoid") local t = script.Parent:WaitForChild("UpperTorso") local pfs = game:GetService("PathfindingService") model.PrimaryPart = hrp while true do wait(2) hum:MoveTo(firstpoint) hum.MoveToFinished:Wait() model:SetPrimaryPartCFrame(hrp.CFrame * CFrame.Angles(0,math.rad(180), 0)) wait(15) hum:MoveTo(secondpoint) hum.MoveToFinished:Wait() wait(15) function getTarget() target = nil for i, v in pairs(game.Workspace:GetChildren()) do human = v:FindFirstChild("Humanoid") torso = v:FindFirstChild("LowerTorso") if human.Parent and torso.Parent == player.Character then target = torso break end end end if target == torso then while wait() do local torso = getTarget() if torso then local path = pfs:CreatePath() path:ComputeASync() local waypoint = path:GetWaypoints() for i, waypoint in pairs(waypoint) do human:MoveTo(torso.Position) human.MoveToFinished:Wait(2) end end end else return target end end
The LowerTorso
has a potential to be nil (player died). You need to account for that case by first checking if the part even exists.
if torso then if human.Parent and torso.Parent == player.Character then target = torso break end end
It is also worth mentioning :Wait()
takes no arguments (the 2 does nothing there.) MoveToFinished
will end when the engine has determined the goal was reached, or timeout after 8 seconds if the humanoid seems stuck.