- Home /
"Simple State Saving" problem.
Hello. I've downloaded a small script for saving and loading data using xml serialization and playerprefs (Simple State Saving; sourcecode below). I wanted to try it out on a very simple test but I have encountered a problem when clearing the key. The LoadData method of the stateStorage class of the downloaded script should return the default value of my class. However the instance of my custom class becomes null instead and i have no idea why. Otherwise the script works fine.
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Data {
public Color _color = Color.red;
}
public class ColorSve : MonoBehaviour {
public Data data = new Data();
// some other variables
void OnGUI() {
redSlider = GUI.HorizontalSlider(redSliderArea, redSlider , 0f ,255f);
//sliders for other colors
UpdateColor();
if(GUI.Button(loadButton, "LOAD")){
data = StateStorage.LoadData<Data>("Data");
if(data == null) Debug.Log("data is null"); //gets logged if I click the button after the clear button
Debug.Log(data._color);
UpdateSlider();
}
// two more buttons which call Statestorage.SaveData / ClearData
}
void UpdateSlider(){
redSlider = data._color.r * 255f;
//same for other sliders
}
void UpdateColor(){
Color temp = new Color (redSlider / 255f, greenSlider /255f, blueSlider /255f, 1f);
data._color = temp;
renderer.material.color = temp;
}
}
Source code of the Simple State Saving class. I only added debug lines and comments.
using UnityEngine;
using System.Xml.Serialization;
using System.IO;
public class StateStorage{
public static T LoadData<T>( string key ){
if ( PlayerPrefs.HasKey( key ) ) {
XmlSerializer serializer = new XmlSerializer( typeof( T ) );
StringReader sr = new StringReader( PlayerPrefs.GetString( key ) );
Debug.Log(PlayerPrefs.GetString(key));
return ( T )serializer.Deserialize( sr );
}else{
Debug.Log("default"); //This gets correctly gets logged after I clear the key
return default(T);
}
}
public static void SaveData<T>( string key, T source ){
XmlSerializer serializer = new XmlSerializer( typeof( T ) );
StringWriter sw = new StringWriter();
serializer.Serialize( sw, source );
PlayerPrefs.SetString( key, sw.ToString() );
Debug.Log(sw.ToString());
}
public static void ClearData( string key ){
PlayerPrefs.DeleteKey( key );
}
}
Answer by Lockstep · Jan 22, 2013 at 10:07 PM
My bad. I misunderstood the default key word. I thought it would return the default class i defined like new Data(); would have done. In reality default always returns 0 (for numeric value types), false (for booleans) or Null (else).