Find nearest object - originalfoo/Prison-Architect-API GitHub Wiki
##Overview
There isn't a function or method to find the closest object, however you can use the range values returned by .GetNearbyObjects() to work it out.
##Example
Let's create a GetNearest( type, range ) function to do the leg work...
-- shortcuts
local find = this.GetNearbyObjects
-- return nearest object, or nil
local function GetNearest( type, range )
local nearest = { range = math.huge } -- current nearest
local results = find( type, range ) -- do the search
-- now find the nearest result
for object, range in next, results do
if range < nearest.range then -- this one is nearer
nearest.range = range
nearest.object = object
end
end
return nearest.object, ( nearest.object and nearest.range or nil )
endAnd here's how to use it (in this example, find the nearest Prisoner entity within a 20 tile radius and kill them; if we don't find one, make a new one and kill that instead):
local prisoner, range = GetNearest( 'Prisoner', 20 )
if prisoner then -- we found nearest prisoner
prisoner.Damage = 100 -- kill prisoner
else -- we didn't find any prisoners...
-- ...so let's spawn a new one and kill that instead :P
prisoner = Object.Spawn( 'Prisoner', this.Pos.x, this.Pos.y )
prisoner.Damage = 100
end