Here are my scripts…hope you like it
Experience.cs
using RPG.Saving;
using UnityEngine;
namespace RPG.Stats
{
public class Experience : MonoBehaviour, ISaveable
{
[SerializeField] float experiencePoints = 0;
[SerializeField] int currentLevel = 1;
ExperienceDisplay displayScript;
BaseStats baseStats;
private void Start()
{
displayScript = FindObjectOfType<ExperienceDisplay>();
baseStats = GetComponent<BaseStats>();
}
public void GainExperience(float xp)
{
experiencePoints += xp;
currentLevel = baseStats.GetLevel();
displayScript.ChangeXpHud(currentLevel);
}
public float GetXp()
{
return experiencePoints;
}
public object CaptureState()
{
return experiencePoints;
}
public void RestoreState(object state)
{
experiencePoints = (float)state;
}
}
}
ExperienceDisplay.cs
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
namespace RPG.Stats
{
public class ExperienceDisplay : MonoBehaviour
{
[SerializeField] Slider xpPercentSlider;
[SerializeField] TextMeshProUGUI xpText;
[SerializeField] TextMeshProUGUI levelText;
Experience xpScript;
BaseStats baseStatsScript;
[SerializeField] ProgressionSO progressionSO;
int currentLevel = 1;
float currentXP;
private void Awake()
{
GameObject player = GameObject.FindWithTag("Player");
xpScript = player.GetComponent<Experience>();
baseStatsScript = player.GetComponent<BaseStats>();
}
IEnumerator Start()
{
yield return new WaitForSeconds(0.1f);
currentLevel = baseStatsScript.GetLevel();
ChangeXpHud(currentLevel);
}
public void ChangeXpHud(int currentLevelFromXpScript)
{
currentLevel = currentLevelFromXpScript;
SetXpText();
SetSliderPercentToNextLevel();
SetLevelText(currentLevel);
}
void SetXpText()
{
currentXP = xpScript.GetXp();
xpText.text = "Total XP = " + currentXP.ToString();
}
void SetSliderPercentToNextLevel()
{
var xpNeeded = progressionSO.GetStat(Stat.ExperienceNeededToLevelUp, CharacterClass.Player, currentLevel);
var xpPercent = currentXP / xpNeeded;
xpPercentSlider.value = xpPercent;
}
public void SetLevelText(int level)
{
currentLevel = level;
levelText.text = "Level " + currentLevel.ToString();
}
}
}