In this course function GetStat()
called every Update()
.
But in case we call it rarely, will Linq be better approach?
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace RPG.Stats
{
[CreateAssetMenu(fileName = "Progression", menuName = "Stats/New Progression")]
public class Progression : ScriptableObject
{
[SerializeField] private ProgressionCharacterClass[] characterClasses;
Dictionary<CharacterClass, Dictionary<Stat,float[]>> lookupTable;
public float GetStat(Stat stat,CharacterClass characterClass, int level)
{
#region Course Approach
BuildLookup();
float[] levels = lookupTable[characterClass][stat];
if(levels.Length < level) return 0;
return levels[level - 1];
#endregion
#region linq
List<ProgressionCharacterClass> progressionCharacterClasses = characterClasses.ToList();
var statValue = from progressionCharacterClass in progressionCharacterClasses
where progressionCharacterClass.characterClass == characterClass
select progressionCharacterClass.stats into progressionStats
from progressionStat in progressionStats
where progressionStat.stat == stat
where progressionStat.levels.Length >= level
select progressionStat.levels[level - 1];
return statValue.First();
#endregion
}
private void BuildLookup()
{
if(lookupTable != null) return;
lookupTable = new Dictionary<CharacterClass, Dictionary<Stat, float[]>>();
foreach(ProgressionCharacterClass progressionClass in characterClasses)
{
Dictionary<Stat, float[]> statLookupTable = new Dictionary<Stat, float[]>();
foreach(ProgressionStat progressionStat in progressionClass.stats)
{
statLookupTable.Add(progressionStat.stat, progressionStat.levels);
}
lookupTable.Add(progressionClass.characterClass, statLookupTable);
}
}
[Serializable]
class ProgressionCharacterClass
{
public CharacterClass characterClass;
public ProgressionStat[] stats;
}
[Serializable]
public class ProgressionStat
{
public Stat stat;
public float[] levels;
}
}
}