So I recently made a game that involves using towers to kill enemies and it locks on to enemies within it's range. However the function that does this seems to cause a lot of lag when it does, and in order for me to check if an enemy is near, I have to use a 'while true do' that goes through every enemy in the enemy folder and checks if it's magnitude from the tower is less than the towers range. I think there is a more efficient way to do this, but I'm not sure. Here's a couple links for images.
https://gyazo.com/80f223c7f11938711bc7488978b293ac
Anything within the blue circle it will shoot. However this is how I made it function.
local function getNearestEnemy() local lowest = 500 local nearObj local children = #enemyFolder:GetChildren() for i, v in pairs(enemyFolder:GetChildren()) do local rootPart = v:FindFirstChild('HumanoidRootPart') if rootPart ~= nil then local health = v:FindFirstChild('Health') if health ~= nil then local groundPos = hitbox.Position - Vector3.new(0, hitbox.Size.Y / 2, 0) local mag = (groundPos - rootPart.Position).magnitude if health.Value >= 1 then if mag <= range.Value then if mag < lowest then nearObj = v lowest = mag end end end end end if i == children then return nearObj end end end spawn(function() while true do wait(.1) if enemy == nil then local nearestEnemy = getNearestEnemy() if nearestEnemy ~= nil then enemy = nearestEnemy end else if enemy:FindFirstChild('HumanoidRootPart') == nil then enemy = nil else attackEnemy() end end end end)
Some variables that you see may not be included in the code block I provided. There is a big issue with how my towers run though. As you can see, every .1 seconds it will check for nearby enemies. That means every second, it has gone through the enemy folder, 10 times. Which I think can easily be seen as a cause of lag. What I want to do is trigger a towers attack when an enemy gets close enough. How might I go about changing this into that type of system?