Another solution for GetStat()

If you’re into linq here’s another solution:

        public float GetStat(Stat stat, CharacterClass characterClass, int level)
        {
            try
            {
                var charClass = characterClasses.First(c => c.characterClass == characterClass);
                var charStat = charClass.stats.First(s => s.stat == stat);
                return charStat.levels[level - 1];
            }
            catch (Exception) // should never get here
            {
                return 0;
            }
        }
1 Like

Amazing solution, just keep in mind that Linq might not be that good in games because it’s a little slower, I don’t think you’ll come across an issue during the project, but for big games it might be an issue, specially if used very frame, which, if I remember correctly, this isn’t the case.

I tend to agree… I’m a huge fan of Linq, but GetStat gets called a LOT, multiple times per Update loop. Each Linq clause puts a copy of the collection onto the heap, and over time this will create a lot of garbage collection.

I have to agree with both you. I was trying to address the nested foreach ‘haters’ :slight_smile:, as I think it improves its Big-O. Anyway, as I found out is a few lesson later, there is a much better solution!

An O(1) solution!

Believe you me, I’m not a huge fan of nested foreaches either, especially ones that might be called a dozen times in an Update cycle.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms