The enemy npcs are inside of a model, because they share a model with a regeneration part(giving them a respawn time). This means that the script below won't make another npc able to go to it.

local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100
	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) and (temp2.Name ~= script.Parent.Config.Owner.Value)  then
			temp = temp2:findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) and human.Parent.Config.attackle.Value == true then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end




while true do
	wait(1)
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end

end

Below is my attempt to make it able to attack the respawning npcs.

local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.Name == "mob") and (temp2 ~= script.Parent) and (temp2.Name ~= script.Parent.Config.Owner.Value)  then
			temp = temp2:findFirstChild():findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild():findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) and human.Parent.Config.attackle.Value == true then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end




while true do
	wait(1)
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end

end

I named the model carrying the respawn part, and the npc, "mob", and I thought that if I used :findFirstChild without any specification on the child's name it would just get the first one(Because the first child in the model is the npc itself). That didn't work though. The reason I did :findFirstChild is because the name of the npc can be anything, bandit, undead, etc, so I couldn't specify.

1 comment

0

Don't come on this site with free model code, expecting for it to be fixed.