NPC pathfinding bug

so this is a script that makes an npc to follow a player until the player leaves a range that is given in the script, problem is when i add multiple npcs close to eachother the script stops working for all of them and they will only stay still, how do i fix this issue?

script:

  function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 50
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("HumanoidRootPart")
		human = temp2:findFirstChild("Humanoid")
		if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
			if (temp.Position - script.PartSu1.Position).Magnitude < dist then
				torso = temp
				dist = (temp.Position - script.PartSu1.Position).Magnitude
			end
		end
	end
end
return torso
end


while true do
    wait(math.random(1,2))
        local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
            if target ~= nil and not target.Parent:findFirstChild("NPC") then
 	       script.Parent.Humanoid:MoveTo(target.Position, target)
       else
	        script.Parent.Humanoid:MoveTo(script.PartSu.Position, script.PartSu)
    end

  end

maybe loop through the players instead of workspace

local Players = game:GetService("Players")

function findNearestTorso(pos)
	local list = Players:GetPlayers()
	local torso = nil
	local dist = 50
	local temp = nil
	local human = nil
	local temp2 = nil

	for x = 1, #list do
		temp2 = list[x].Character
		
		if not temp2 then
			continue
		end
		
		temp = temp2:findFirstChild("HumanoidRootPart")
		human = temp2:findFirstChild("Humanoid")

		if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
			if (temp.Position - script.PartSu1.Position).Magnitude < dist then
				torso = temp
				dist = (temp.Position - script.PartSu1.Position).Magnitude
			end
		end
	end

	return torso
end

while true do
	wait(math.random(1,2))

	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil and not target.Parent:findFirstChild("NPC") then
		script.Parent.Humanoid:MoveTo(target.Position)
	else
		script.Parent.Humanoid:MoveTo(script.PartSu.Position)
	end
end

What if he wants NPC vs NPC aswell?

Tho sure at that point might be aswell tag all NPCs and the player with a tag using CollectionService

Or just use game.Players:GetPlayerFromCharacter(CharacterModel) and check if it’s nil or not to see if it’s a player.

wouldn’t they fight with each other then?

this worked thank you so much!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.