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