Pathfinding stops following player after death

I am finalising my pathfinding AI however it stops following the player if they die and then respawn, and instead stands still or sometimes pathfind to somewhere random and then stands still.

The AI uses the SimplePath Module:

Here is the script in the AI (I am new to this so it could seem very messy, any help appreciated):

local character = script.Parent
local Humanoid = character:WaitForChild("Humanoid") 
local root = character.HumanoidRootPart
local Players = game:GetService("Players")
local SimplePath = require(workspace.SimplePath)
local Path = SimplePath.new(script.Parent)

Path.Visualize = true 

	for _, child:Instance in pairs(character:GetChildren()) do
		if child:IsA("BasePart") and not child.Anchored then
			child:SetNetworkOwner(nil)
		end

local path
local waypoint

local chaseName = nil

function getHumanoid(model)
	for _, v in pairs(model:GetChildren())do
		if v:IsA'Humanoid' then
			return v
		end
	end
end

local human = getHumanoid(character)

function GetTorso(part)
	local chars = game.Workspace:GetChildren()
	local chaseRoot = nil
	local chaseTorso = nil
	local chasePlr = nil
	local chaseHuman = nil
	for i = 1, #chars do
		chasePlr = chars[i]
		if chasePlr:IsA'Model' and chasePlr ~= character then
			chaseHuman = getHumanoid(chasePlr)
			chaseRoot = chasePlr:FindFirstChild'HumanoidRootPart'
			if chaseRoot ~= nil and chaseHuman ~= nil and chaseHuman.Health > 0 and chaseHuman.Name ~= "Zombie" then
					chaseName = chasePlr.Name
					chaseTorso = chaseRoot
				end
			end
		end
	return chaseTorso
end

function GetPlayersBodyParts(t)
	local torso = t
	if torso then
		local figure = torso.Parent
		for _, v in pairs(figure:GetChildren())do
			if v:IsA'Part' then
				return v.Name
			end
		end
	else
		return "HumanoidRootPart"
	end
end

while wait() do
	local nrstt = GetTorso(root.Position)
	if nrstt ~= nil and human.Health > 0 then -- if player detected	
		local function checkw(t)
			local ci = 3
			if ci > #t then
				ci = 3
			end
			if t[ci] == nil and ci < #t then
				repeat ci = ci + 1 wait() until t[ci] ~= nil
				return Vector3.new(1,0,0) + t[ci]
			else
				ci = 3
				return t[ci]
			end
		end
				
		while true do
				Path:Run(nrstt)
				wait()
				end
			end
		end
	end

I have just started using this module so any help is appreciated
Thanks :slight_smile:
-Xander

I haven’t used simple path before, but have a look at this part of your code:

		while true do
				Path:Run(nrstt)
				wait()
			end
		end

Once you’ve found the player’s root part, you enter this loop which will never end because the condition is always true. Because it never ends, it never gets to look for a new player to attack once the original player it found is dead.

while nrstt ~= nil and nrstt.Parent ~= nil and nrstt.Parent.Humanoid.Health > 0 do
	Path:Run(nrstt)
	wait()
end

This should check to see if the player it’s attacking is dead, and if it is then it should stop following a path to them.

1 Like