[LUA QUESTION] Get Nearest City to Unit

Tryhard Trevor

Chieftain
Joined
Feb 29, 2016
Messages
22
Currently working on a custom Civ. I'm trying to setup some Lua. My end goal is to make it to where when a Great Engineer is expended building a Manufactory, it will provided some production to the nearest city. In order to do this, I'm using the GameEvents.UnitPrekill.Add hook, and when the unit is deleted I get the units plot. When I have the plot, I use the GetPlotCity() method to return the city, however, this method is always returning NIL. Am I using it incorrectly? Is there a better way I could accomplish this goal?
 
Code:
function GetNearestCity(pPlot, pPlayer)
	local iShortestDistance = 99999
	local pNearestCity = nil

	local iUnitX, iUnitY = pPlot:GetX(), pPlot:GetY()

	for pCity in pPlayer:Cities() do
		local iDist = Map.PlotDistance(pCity:GetX(), pCity:GetY(), iUnitX, iUnitY)
		if (iDist < iShortestDistance) then
			iShortestDistance = iDist
			pNearestCity = pCity
		end
	end
	return pNearestCity
end

Call it as a local variable in a function, e.g.:
local pCity = GetNearestCity(pPlot, pPlayer)
(both pPlot and pPlayer must be defined before this function is called)
 
GetPlotCity() returns the city in the given plot - as you've just built a Manufactory in the plot, by definition there cannot be a city in it as well, hence why it's return nil
 
Back
Top Bottom