Static Class Strings not truly null?
I have a Class for my game that controls the player's hand. It has a boolean called handFull, and when it is true the button that causes the player to grab an object doesn't work. The hand is full, see?
I also have a seperate Class that handles persisting data between scene transitions. It handles player inventory and triggers for the game at large. It is called Persistence. I built it with a public static variable of itself, so that it can be accessed by other Classes in the game (If you've watched the Unity tutorial on Data Persistance, I basically have that, with more variables being remembered) . The player has one inventory slot, and it is handled by a string.
I want the handFull state to persist between scene changes. After all, if you have a Sword in your inventory and your hand is full (handFull == true), it wouldn't do if you shifted scenes, the sword remained in your inventory, but handFull (handled by a non-persistant Class) is suddenly false.
So I wrote some code. It looked like this:
void Awake (){
If (Persistance.mem.Inventory == null){
handFull = false
}else{
handFull = true;
}
But every time I ran the script for testing, the game loaded, and handFull was set to true. I went to the Persistance Class, and defined the string Inventory as null, but it did not work. Eventually, I ended up creating a long list of 'Or' statements (if he's not holding a sword or a shield or a bottle or a... then the hand is empty). It works, for this game, but I'd like to have a bit more elegance in my future projects.
What the hell did I do wrong?
Are you sure nothing is settings a non-null value to inventory? Show the inventory value in the console and you might see what's changing it
Well, I thought nothing was setting it to null, as I set up the variable inventory as = null; initially. But clearly I was wrong. How would I check it in the console?
Is handFull defined as a public variable? If so, it is possible that Unity serializes the value somewhere in the editor, causing the value to be set when you start the game.
It is a public variable, but I am pretty sure it's the script that's flipping it to true, since if I remove the script I can set it to whatever I want and it stays unchanged.
Answer by gcoope · Aug 25, 2016 at 01:21 PM
Instead of if(Persistance.mem.Inventory == null)
try using if(string.IsNullOrEmpty(Persistance.mem.Inventory))
to check the status of the string. This does as you would expect, checking that that object isn't null, as well as checking if the value of it isn't blank
Thank you! This does what I need to do. Though I am still curious why a string initialized as = null; isn't reading as = null;.