My game’s FSM is based on utility stats which each NPC curates indicating how much they need to eat, poo, flee from danger, and the like. Currently I use a very cumbersome implementation that I wrote when I was first learning to program:
int highestValue;
activityArray [0] = npc.BathroomNeed; //NPC's urge to use bathroom
activityArray [1] =npc.FoodNeed; //Urge to eat
activityArray[2] = npc.SafetyNeed; //Urge to run away
highestValue = FindMax (activityArray); //Return the index of the array element with the highest value
if (highestValue == 1)
//Transition to FSM state.Bathroom
else if (highestValue == 2)
//Transition to FSM state.Food
else
//Transition to FSM state.RunAway
BathroomNeed, FoodNeed, and SafetyNeed are all ints between 0-100 indicating how much the NPC wants to do that action, and I set my FSM transition by iterating through that list, comparing values until I determine which array index is highest, then I iterate through a second conditional loop to compare the highest index against my list of transitions, then I finally trigger the correct transition within the if block.
This has two obvious problems to me, given that on average this function runs 500-1,000 times/second in my game: #1 is that it is incredibly clunky and slow, and #2 is that it’s hard-coded: every time I modify the AI I’ll need to modify a lot of code, take a very close look at everything, and cross my fingers that I don’t miss anything.
Given that, is there a better way to go about this? All I need to do is a) compare a number of utility stats represented as ints to determine which one is highest, b) set a transition based on which is highest.