The FindPath code is quite expensive and is called twice per Valid Grid Position In the MoveAction and then again when the user (or EnemyAI) decides to move. A couple of people have already suggested combining the HasPath and GetPath Length calls into a single call but, we could go a step further and cache this value.
private Dictionary<string, List<GridPosition>> pathCache = new Dictionary<string, List<GridPosition>>();
Then at the start of GetValidGridPositionList:
pathCache.Clear();
Then when we check Has Path:
List<GridPosition> pathGridPositionList = Pathfinding.Instance.FindPath(unitGridPosition, testGridPosition, out int pathLength);
if (pathLength == 0)
{
// no path found
continue;
}
int pathFindingDistanceMultiplier = 10;
if (pathLength > maxMoveDistance * pathFindingDistanceMultiplier)
{
// point is too far away
continue;
}
pathCache.Add(testGridPosition.ToString(), pathGridPositionList);
and finally in TakeAction:
List<GridPosition> pathGridPositionList;
if (pathCache.ContainsKey(gridPosition.ToString()))
{
pathGridPositionList = pathCache[gridPosition.ToString()];
} else
{
pathGridPositionList = Pathfinding.Instance.FindPath(unit.GetGridPosition(), gridPosition, out int pathLength);
}
I think this can be optimised further by checking if the player or enemy has moved grid position inbetween calls to GetValidActionGridPositionList for the MoveAction.