function Find_Unit_Closest_To_Location takes location WhichLocation returns unit
local group g=CreateGroup()
local unit u
local real v
local real x
local real y
local real newVector=99999 //those are 5 nines
local unit closestUnit
call GroupEnumUnitsInRange( g , GetLocationX( WhichLocation ) , GetLocationY( WhichLocation ) , radius, null(?) )
//Pick every unit in a certain radius (distance) around the location.
//If the point is constant, you can use real numbers (coordinates) instead of the GetLocationXY functions, which will also speed up our custom function
loop
set u=FirstOfGroup(g)
exitwhen u==null
set x = GetUnitX( u ) - GetLocationX( WhichLocation )
set y = GetUnitY( u ) - GetLocationY( WhichLocation )
set v = SquareRoot(x * x + y * y) //Calculating vector norm
if v<newVector then
set newVector = v
set closestUnit = u
endif
//If the calculated distance is bigger than the previous, do nothing.
//If the calculated distance is smaller, this might be the unit we're looking for.
//Therefore, let's set this as the closest unit yet.
//The remaining units can be farther away from the location, in which case they're ignored.
//If a unit is closer, the previous unit is not the closest, so we discard the old unit.
//The loop keeps looping until there are no units left.
call GroupRemoveUnit( g , u )
endloop
call DestroyGroup(g)
set g=null
return closestUnit
endfunction