My initial GetLevel() implementation

Since I started it right away, there was no way to determine the number of available levels at that point. Also, in my logic when you have say 5 levels and query a stat for level 10 you get the level 5 value back (effectively capping that stat at the last entry of its progression table).

    public int GetLevel()
    {
        int currentLevel = 1;
        float nextLevelXP, currentLevelXP;
        do
        {
            currentLevelXP = progression.GetStat(Stats.ExperienceToLevelUp, characterClass, currentLevel);
            nextLevelXP = progression.GetStat(Stats.ExperienceToLevelUp, characterClass, currentLevel + 1);
            if (nextLevelXP == currentLevelXP)
            {
                break;   // no further progression available
            }
            currentLevel++;
        }
        while (nextLevelXP < currentXP);
        return currentLevel;
    }

Initially I also cache the current level and used that value in GetStat() instead of calling GetLevel().

One aspect to consider about calculating the level directly from the player’s current XP would be if one wanted the game to have automatic leveling up, or if it was something the player would have to be doing by themselves. Or maybe the level up is delayed until the end of the current combat.

The important thing to consider when caching values is having only one source of truth and it would be that component that would be caching the value and being in the loop for changes.

Actually I didn’t quite think of just adding an Update() to the BaseStats so I do cache the level already inside the Experience component in order to expose it to the ExperienceDisplay where simply I added the level to the output:

        private void Update()
        {
            if (null == experienceValueUI) return;
            experienceValueUI.text = String.Format("{0:0} [{1:0}]", experience.ExperiencePoints, experience.CurrentLevel);
        }

Privacy & Terms