This code checks if there are players close to an npc and if so, it chases and attacks. Currently he can scan up to 300 enemies without loss of performance. Is there anything that can improve? I really want to optimize it
local folder = workspace.Folder --Folder with enemies
local array = folder:GetChildren()
local deleyBetweenVerifications = 3
local distanceForChase = 15
local distanceForAttack = 5
local attackDeley = 0.5
local function attack(humanoid, plrHumanoid, part, hrp)
while humanoid.Health >= 0 and (hrp.Position - part.Position).Magnitude < distanceForChase do
humanoid:MoveTo(part.Position, part)
if (hrp.Position - part.Position).Magnitude < distanceForAttack and plrHumanoid and plrHumanoid.Health >= 0 then
plrHumanoid.Health = plrHumanoid.Health - 10
end
wait(attackDeley)
end
end
local function Verification()
while wait(deleyBetweenVerifications) do
for x = 1, #array do
wait(0.001)
local hrp = array[x].HumanoidRootPart
local posX = hrp.Position.X - distanceForChase
local posY = hrp.Position.Y - 2
local posZ = hrp.Position.Z - distanceForChase
local posTable = workspace:FindPartsInRegion3WithIgnoreList(Region3.new(
Vector3.new(posX - distanceForChase, posY, posZ - distanceForChase),
Vector3.new(posX + distanceForChase, posY+4, posZ + distanceForChase)),
{folder}, --descendants to ignore
50) -- max of objects that will returned
for z = 1, #posTable do
local part = posTable[z]
if part.Name == "HumanoidRootPart" and part.Parent.ClassName == "Model" and part.Parent:FindFirstChildOfClass("Humanoid") then
local humanoid = array[x].Humanoid
coroutine.wrap(attack)(humanoid, part.Parent.Humanoid, part, hrp)
end
end
end
end
end
spawn(Verification)