Counting Units by Type
Some logic might need to know how many of a particular type of unit the AI currently controls. To do this I suggest the following
Here’s an example implementation:
- Add an empty module
- This module will have a table such that tableobject[unittype] = XofThisType
- Everytime a unit of yours is built, increment the number
- Decrement on unit death
- To get the number of units for say a corsolar, all you would need to do now is local solarCount = tableobject[“corsolar”] or something similar.
UnitTypeCounter = class(Module) function UnitTypeCounter:Name() return "UnitTypeCounter" end function UnitTypeCounter:internalName() return "TypeCounter" end function UnitTypeCounter:Init() self.typeCount = {} end function UnitTypeCounter:UnitCreated(engineunit) if engineunit:Team() == game:GetTeamID() then local t = engineunit:Type() local name = t:Name() local count = 0 if self.typeCount[name] ~= nil count = self.typeCount[name] end self.typeCount = count + 1 end end function UnitTypeCounter:UnitBuilt(engineunit) end function UnitTypeCounter:UnitDead(engineunit) if engineunit:Team() == game:GetTeamID() then local t = engineunit:Type() local name = t:Name() local count = 0 if self.typeCount[name] ~= nil count = self.typeCount[name] end self.typeCount = count - 1 end end