This question was
closed Dec 25, 2016 at 12:24 AM by
NNLV for the following reason:
Found the bug, and it's fixed now :)
Question by
NNLV · Dec 22, 2016 at 09:16 PM ·
c#programmingloadsaveloadloading file
Saving and Loading from scene to scene..
C# problems.
I'm currently having some troubles about saving and loading in different scenes, here's my code thnx in advance :)
In both:
private int totalCoins;
In the game:
public void Save()
{
if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = new PlayerData();
data.Coins = totalCoins;
bf.Serialize(file, data);
file.Close();
}
else
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.CreateNew);
PlayerData data = new PlayerData();
data.Coins = totalCoins;
bf.Serialize(file, data);
file.Close();
}
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
totalCoins = data.Coins;
}
}
[Serializable]
class PlayerData
{
public int Coins;
}
In main menu, upgrades:
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
totalCoins = data.Coins;
}
}
[Serializable]
class PlayerData
{
public int Coins;
}
It works fine in the "game" scenes, but it doesn't show up in upgrades....
Exceptions: nvalidCastException: Cannot cast from source type to destination type. GameSave.Load () (at Assets/Scripts/GameSave.cs:30) GameSave.Start () (at Assets/Scripts/GameSave.cs:15)
Line 15:
void Start () {
15 Load();
totalPointText.text = "Coins: " + totalCoins.ToString();
}
Line 30:
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
30 PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
totalCoins = data.Coins;
}
}
Comment