So I took on the challenge and got a NullReferenceException in my BaseStats.cs file.
The line it’s referring to (see below) is the onLevelUp() call within the UpdateLevel() method. I then followed what the video showed and the code is near (as far as I can see at the moment) identical.
Anyone have any thoughts on what I did wrong?
using GameDevTV.Utils;
using RPG.Resources;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Stats
{
public class BaseStats : MonoBehaviour
{
[Range(1,99)]
[SerializeField] int startingLevel = 1;
[SerializeField] CharacterClass characterClass;
[SerializeField] Progression progression = null;
[SerializeField] GameObject levelUpParticleEffect = null;
[SerializeField] bool shouldUseModifiers = false;
public event Action onLevelUp;
LazyValue<int> currentLevel;
Experience experience;
private void Awake()
{
experience = GetComponent<Experience>();
currentLevel = new LazyValue<int>(CalculateLevel);
}
private void Start()
{
currentLevel.ForceInit();
}
private void OnEnable()
{
if (experience != null)
{
experience.onExperienceGained += UpdateLevel;
}
}
private void OnDisable()
{
if (experience != null)
{
experience.onExperienceGained -= UpdateLevel;
}
}
private void UpdateLevel()
{
int newLevel = CalculateLevel();
if (newLevel > currentLevel.value)
{
currentLevel.value = newLevel;
LevelUpEffect();
onLevelUp(); //Error is generated right on this line
}
}
private void LevelUpEffect()
{
Instantiate(levelUpParticleEffect, transform);
}
public float GetStat(Stat stat)
{
return (GetBaseStat(stat) + GetAdditiveModifier(stat)) * (1 + GetPercentageModifier(stat)/100);
}
private float GetBaseStat(Stat stat)
{
return progression.GetStat(stat, characterClass, GetLevel());
}
public int GetLevel()
{
return currentLevel.value;
}
private float GetAdditiveModifier(Stat stat)
{
if (!shouldUseModifiers) return 0;
float totalModifiers = 0;
foreach(IModifierProvider provider in GetComponents<IModifierProvider>())
{
foreach (float modifier in provider.GetAdditiveModifiers(stat))
{
totalModifiers += modifier;
}
}
return totalModifiers;
}
private float GetPercentageModifier(Stat stat)
{
if (!shouldUseModifiers) return 0;
float totalModifiers = 0;
foreach (IModifierProvider provider in GetComponents<IModifierProvider>())
{
foreach (float modifier in provider.GetPercentModifier(stat))
{
totalModifiers += modifier;
}
}
return totalModifiers;
}
private int CalculateLevel()
{
Experience experience = GetComponent<Experience>();
if (experience == null) return startingLevel;
float currentXP = experience.GetExperience();
int penultimateLevel = progression.GetLevels(Stat.ExperienceToLevelUp, characterClass);
for (int level = 1; level <= penultimateLevel; level++)
{
float XPtoLevelUp = progression.GetStat(Stat.ExperienceToLevelUp, characterClass, level);
if (XPtoLevelUp> currentXP)
{
return level;
}
}
return penultimateLevel + 1;
}
}
}