While working on my npc script, I came across a problem. So bascilly I want to make it so that the npc repeatedly find a target, so when player respawns the npc can still find their rootpart. But problem is after the player dies, the npc doesn’t work anymore. It just stops. The error is on line 20
Here is the script:
local pathfindingservice = game:GetService("PathfindingService")
local dummy = script.Parent
local dummyHumanoid = script.Parent:WaitForChild("Humanoid")
local dummyRootPart = script.Parent:WaitForChild("HumanoidRootPart")
target = nil
function findTarget()
if dummyHumanoid.Health > 0 then
for i,v in pairs(game.Workspace:GetDescendants()) do
if v:IsA("Model") then
if v.Name ~= dummy.Name and v:FindFirstChild("HumanoidRootPart") and v:FindFirstChild("Humanoid").Health > 0 then
target = v.HumanoidRootPart
vHumanoid = v.Humanoid
local path = pathfindingservice:CreatePath()
path:ComputeAsync(dummyRootPart.Position,target.Position)
if path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
for i,waypoint in pairs(waypoints) do
if check() <= 100 and target ~= nil then
dummyHumanoid:MoveTo(waypoint.Position)
dummyHumanoid.MoveToFinished:Wait()
if check() <= 2 then
vHumanoid:TakeDamage(5)
wait(1)
print("Taking damage, npc close")
if vHumanoid.Health == 0 then
target = nil
print("Target dead")
end
end
end
end
end
end
end
end
end
end
function check()
if vHumanoid.Health > 0 then
if target then
magnitude = (dummyRootPart.Position - target.Position).Magnitude
return magnitude
end
end
end
while wait() do
findTarget()
end