Apologies in advance for incorrect terminology. I've borrowed script that saves/loads data, which I can use by referencing an interface that has a save and load method. Say I have script1, with a variable called playerHealth, I can then inherit the interface, call the save and load methods, and in those methods basically write that playerHealth, when saved, replaces the playerHealth variable in the Gamedata script (which houses initial values, or 0 in this case). and when loaded, the playerHealth value in the save file replaces the playerHealth in script1.
Problem is, clicking the save button, which has attached to it a function to find all variables within all save/load method instances in the various scripts, script1 (playerHealth), script2 (enemyHealth), etc., and execute the save sequence, which replaces all those variables in the gamedata script to the updated values, gives me an error:
NullReferenceException: Object reference not set to an instance of an object
Looking at the specifics of the error, it points me to the save method called in script1, where there's only this single line of code
public void SaveData ( GameData data )
{
data.playerHealth = playerHealth;
}
playerHealth in this case would be a public int.
To me, this code seems to make sense? When I click the save button, it should do everything mentioned above, meaning it will find this section in script1, reference current playerHealth in script1, and make the playerHealth in the save file equal to the current playerHealth. But the error pops up regardless.
What did I do to try and fix the issue
Well, not much, as I'm kind of stuck on what to do. I tried adding a debug.log before the single line of code to see if playerHealth actually has a value attached at that point, and it outputs the correct value. So playerHealth, at the point in code just before replacing the savefile value, does indeed have a current value.
Edit
It is most likely data.playerHealth
throwing the error from my subsequent attempts. But then it really doesn't make much sense to me. Here's the gamedata.cs file that the above line of code would reference:
[System.Serializable]
public class GameData
{
public int playerHealth;
public GameData()
{
this.playerHealth = 0;
}
}
As you can see, I've set a value. So no reason why it should throw an object reference error, right?