- Home /
Question by
ColonelOme · Dec 21, 2017 at 08:31 AM ·
c#reflectionsave dataloading filefieldinfo
Object type System.Boolean cannot be converted to target type: System.Int32 ?
Hello. I'm trying to save my game using reflection to save the fields for all my character's stats. The files save fine..
but when I try loading the game i get this:
To me, it seems like when I try deserializing the file to load the data, it loads it backwards and then tries to apply the values to the current script but in the wrong order. As you can see from the log it saves the curHP first and is Dead last but when it tries loading, it tries loading isDead into curHP. I tried reversing the Array to get the correct values but it still gives me a similar error during the 3rd element, just with a different type (which is the Weapon secondary)
[Serializable]
class PlayerData
{
public FieldInfo[] unityFields;
public object uValue;
public PlayerData ()
{
Type unityType = typeof(UnityChan);
unityFields = unityType.GetFields();
foreach (FieldInfo field in unityFields)
{
uValue = field.GetValue(GameManager.instance.ub);
Debug.Log(field.ToString());
Debug.Log(field.GetValue(uC).ToString());
}
}
}
public void SaveGame()
{
PlayerData playerdata = new PlayerData();
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/save.dat");
bf.Serialize(file, playerdata);
file.Close();
gameSaved = true;
}
public void LoadGame()
{
if (File.Exists(Application.persistentDataPath + "/save.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/save.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
uFields = data.unityFields;
foreach (FieldInfo field in uFields)
{
Debug.Log(field.ToString());
field.SetValue(ub, data.uValue);
}
Debug.Log("Game Loaded!");
}
else
{
Debug.LogError("No saved data!");
}
}
private static UnityChan uC;
private static FieldInfo[] uFields;
}
screenshot-14.png
(80.2 kB)
screenshot-16.png
(74.1 kB)
Comment