How should I handle situations where NPC fleets don't have a commander? Or their commander exists but doesn't have stats?
People are getting crashes with my mod because I'm modifying NAVIGATION_PENALTY_MULT. This is fine most of the time, but if there is nothing to reference for that the game crashes with a null pointer exception.
I'm trying to set things up so my code gracefully handles this situation, and still ends with the NPC fleet getting the bonus correctly.
Code in question
private static void applyHarmonics(CampaignFleetAPI fleet)
{
PersonAPI commander = fleet.getCommander();
MutableCharacterStatsAPI commanderStats;
if (commander == null)
{
commander = Global.getFactory().createPerson();
fleet.setCommander(commander);
}
if (fleet.isPlayerFleet())
{
commanderStats = Global.getSector().getPlayerStats();
}
else
{
commanderStats = commander.getFleetCommanderStats();
}
if (commanderStats == null)
{
commander.setStats(new CharacterStats());
}
float currentNavPenalty = commanderStats.getDynamic().getStat(Stats.NAVIGATION_PENALTY_MULT).getModifiedValue();
FleetDataAPI fleetData = fleet.getFleetData();
MutableFleetStatsAPI fleetStats = fleetData.getFleet().getStats();
boolean hasHarmonics = fleetStats.hasMod(HARMONIC_ID);
boolean hasHarmonicMod = false;
for (FleetMemberAPI member : fleet.getFleetData().getMembersListCopy()) {
if (member.getVariant().hasHullMod("stardust_WarpHarmonicResonator"))
{
hasHarmonicMod = true;
break;
}
}
if (hasHarmonics == false && hasHarmonicMod == true)
{
commanderStats.getDynamic().getStat(Stats.NAVIGATION_PENALTY_MULT).modifyFlat(HARMONIC_ID,
-0.01f * stardust_WarpHarmonicResonator.NAVIGATION_PENALTY_REDUCTION);
MutableStat fleetChecked = new MutableStat(0.0F);
fleetStats.addTemporaryModMult(365f, HARMONIC_ID, HARMONIC_DESC, 1f, fleetChecked);
}
else if (hasHarmonics == true && hasHarmonicMod == false)
{
//commanderStats.getDynamic().getStat(Stats.NAVIGATION_PENALTY_MULT).modifyFlat(HARMONIC_ID,
// 0.01f * stardust_WarpHarmonicResonator.NAVIGATION_PENALTY_REDUCTION);
commanderStats.getDynamic().getStat(Stats.NAVIGATION_PENALTY_MULT).unmodify(HARMONIC_ID);
fleetStats.removeTemporaryMod(HARMONIC_ID);
}
}
The chunk of code at the top is what I have in to handle things, but it still doesn't solve my problem. When it gets down to grabbing the current Nav Penalty, it crashes out on the null pointer because even if I do create a commander and initialize Stats for them.
What do I need to do to get this to work properly?
I could catch the errors so it doesn't crash, but I'd much rather have it put the game into a correct state so NPC fleets also get the intended bonus from this ship being in their fleet.
[update]
I have noticed that
commanderStats = fleet.getCommanderStats();
ends up giving me nulls much less often. Does not help for what to do if nulls show up, though.