I am developing a tower defense style game. When the towers shoot, they shoot at random enemies in range, and it doesn't get the one that's closest to the end. I have tried if functions and it still doesn't get the first one. The code below gets an enemy in range that exists. However, it always shoots the enemy that is the farthest away from the end when in fact I want the opposite.
local closestpart
for n,e in pairs(workspace.Game.Enemies:GetChildren()) do
if e ~= nil then
local mag = (tower.PrimaryPart.Position-e.PrimaryPart.Position).magnitude
if mag <= script.Parent.Range.Value then
closestpart = e
end
end
end
I have a source value, which says where it is on the map, but I cant seem to find out how to get that to make the towers ALWAYS shoot the first enemy that is in range.

3 comments
does it shoot the first enemy in range at least the first time?
Sorry, late response. It only does that with one enemy, usually it attacks the first one that appears on the map.
does it shoot the first enemy in range at least the first time?