Hello developers,
So i am currently making an NPC attacking system more specifically laser attacks which will damage a target every 0.08 seconds if they are in range. Unfortuantely since this cool down is very short, that means everytime it finishes the cooldown, it will have to loop through a folder of all the enemies to find if a target is in range and which target is the closest. Is there more of a simple way to find the closest target instead of looping through a folder of around 50 enemies? It causes severe lag on the game when testing. More specifically, how does a game like TDS combat this since they can handle multiple troops with very short cooldown and lots of enemies without lag. Any help would be appreciated!
For more information, everytime it runs the function it will use this to check for the closest target:
function module.LocateTarget(currenttowerhrp, range)
local target = nil
if #workspace.RaidStuff.RaidEnemys:GetChildren() <= 0 then return end
for i, v in ipairs(workspace.RaidStuff.RaidEnemys:GetChildren()) do
if v:FindFirstChild("HumanoidRootPart") and v:FindFirstChild("Humanoid") and v:FindFirstChild("Humanoid").Health > 0 then else continue end
local distance = (v.HumanoidRootPart.Position - currenttowerhrp.Position).Magnitude
if distance < range then
target = v
range = distance
end
end
return target
end
If you have some sort of path system, you could try culling the list via it. If that’s not possible, try culling the list via the spatial query api (you would need to do testing to find out if it’s faster). Either way, you should cut down on the number of FindFirstChilds and try removing the check for length <= 0 (not much of gain, but it’s something).
On an alternate route, I would recommend checking to make sure that it’s just this function and not what you do with its output that is causing the lag.
1 Like