Unit target system not working right(tower

Hey so my units keep hitting the enemys even when they are out of range. But it doesnt do that with the near target mode

Heres part of the script

function units.FindTarget(newUnit, range, mode)
	local bestTarget = nil
	
	local bestGoTo = nil
	local bestDistance = nil
	local bestHealth = nil
	
	for i, foodEnemy in ipairs(workspace.FoodEnemys:GetChildren()) do
		local distanceToFoodEnemy = (foodEnemy.HumanoidRootPart.Position - newUnit.HumanoidRootPart.Position).Magnitude
		local distanceToGoTo = (foodEnemy.HumanoidRootPart.Position - map.GoTos[foodEnemy.GoingTo.Value].Position).Magnitude
		
		if mode == "Near" then
			if distanceToFoodEnemy <= range then
				range = distanceToFoodEnemy
				bestTarget = foodEnemy
		    end
			elseif mode == "First" then
				if not bestGoTo or foodEnemy.GoingTo.Value >= bestGoTo then
					if bestGoTo then
						bestDistance = nil
					end
					bestGoTo = foodEnemy.GoingTo.Value
					
					if not bestDistance or distanceToGoTo < bestDistance then
						bestDistance = distanceToGoTo
						bestTarget = foodEnemy
					end
				end
			elseif mode == "Last" then
				if not bestGoTo or foodEnemy.GoingTo.Value <= bestGoTo then
					bestGoTo = foodEnemy.GoingTo.Value

					if not bestDistance or distanceToGoTo > bestDistance then
						bestDistance = distanceToGoTo
						bestTarget = foodEnemy
					end
				end
			elseif mode == "Strong" then
				if not bestHealth or foodEnemy.Humanoid.Health > bestHealth then
					bestHealth = foodEnemy.Humanoid.Health
					bestTarget = foodEnemy
			     end
			elseif mode == "Weak" then
				if not bestHealth or foodEnemy.Humanoid.Health < bestHealth then
					bestHealth = foodEnemy.Humanoid.Health
					bestTarget = foodEnemy
				end
			end
		end
	
		return bestTarget
	end

It would seem that none of the code runs if mode is not near, so it doesn’t make sense to then check if it’s something else?

yea i noticed that but im not sure how to fix it