Hi guys,
Before reading on, note that I also completed the Displaying Experience lecture before writing this post.
I’m noticing some weird behavior with the saving system and experience points. If I kill an enemy and manually save by pressing S, then it saves the experience.
I can tell because when I press L to load, it still shows 10 XP, which is what I got from killing the enemy. No error messages, nothing at all. Everything’s fine when I do this.
However, now, when I enter a different scene, the XP resets to 0. In addition, I get a bunch of red warnings when I switch scenes:
Following the errors, I looked at my experience display script in update. Here is the ExperienceDisplay script:
using System;
using UnityEngine;
using UnityEngine.UI;
namespace RPG.Attributes
{
public class ExperienceDisplay : MonoBehaviour
{
Experience experience;
Text xpText;
private void Awake()
{
experience = GameObject.FindWithTag("Player").GetComponent<Experience>();
xpText = gameObject.GetComponent<Text>();
}
private void Update()
{
xpText.text = string.Format("{0:0}", experience.GetPoints());
}
}
}
I noticed if I add if (experience == null) return;
right before setting the text, the log messages go away, but the XP still doesn’t load properly. I’m not sure if it’s something to do with how I wrote the experience display script, or if I messed up something in the saving system or even switching between scenes.
For reference, here is Experience.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Saving;
namespace RPG.Attributes
{
public class Experience : MonoBehaviour, ISaveable
{
[SerializeField] float experiencePoints = 0;
public void GainExperience(float experience)
{
experiencePoints += experience;
}
public float GetPoints()
{
return experiencePoints;
}
public object CaptureState()
{
return experiencePoints;
}
public void RestoreState(object state)
{
experiencePoints = (float)state;
}
}
}
Thanks for your time and help!