Hi! I’m currently working on a game where I need a unit to find the closest target. In this function, the unit looks in a radius around itself and detects if there is a target within the radius, if not, it searches the entire group of targets (A table). Problem is, when I’m calling this function for 200 units, it gets VERY resource intensive. Does anyone have any Ideas or insights to make it faster?
function FindClosest(UnitSpecified, UnitPropertiesSpecified)
local Params = OverlapParams.new()
Params.RespectCanCollide = false
local UnitPos = UnitSpecified.HumanoidRootPart.Position
local UnitsClose = workspace:GetPartBoundsInRadius(UnitPos, 10, Params)
local PotentialTargets = {}
local UnitParentName = UnitSpecified.Parent.Name
for _, Object in pairs(UnitsClose) do
local ObjectParent = Object.Parent
if Object.Name == "HumanoidRootPart" and ObjectParent:IsA("Folder") then
if ObjectParent.Humanoid.Health ~= 1 and ObjectParent.Parent.Name ~= UnitParentName then
table.insert(PotentialTargets, ObjectParent)
end
end
end
if #PotentialTargets == 0 then
PotentialTargets = UnitPropertiesSpecified["Attacking"]:GetChildren()
end
local closestTarget = nil
local minDistance = math.huge
for i, Target in pairs(PotentialTargets) do
local TargetRoot = Target:FindFirstChild("HumanoidRootPart")
if TargetRoot then
local Distance = (UnitPos - TargetRoot.Position).Magnitude
if Distance < minDistance then
minDistance = Distance
closestTarget = Target
end
end
end
return closestTarget, minDistance
end