So, what I am trying to do is to save a float and a string into a database so that I can use those values later in a persistent highscore table.
I've come that far that I'm able to save the data, and the more entries I feed the Save function, the bigger the file becomes. So I'm assuming, that works.
When I want to deserialize the file in order to read and construct a scoretable, I get this error:
InvalidCastException: Cannot cast from source type to destination type. loadHighScore.LoadFromFile () (at Assets/scripts/GameManager/loadHighScore.cs:40)loadHighScore.Start () (at Assets/scripts/GameManager/loadHighScore.cs:18)
Here are the two scripts:
highscoreCounter:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class highscoreCounter : MonoBehaviour
{
public static highscoreCounter control;
public int highScoreFinal;
public string playerName;
void Update()
{
highScoreFinal = GetComponent<highscoreCalculator>().highScoreFinal;
playerName = GameObject.Find("LevelFinisher").GetComponent<finishLevel>().newPlayerName;
SaveToFile();
}
public void SaveToFile()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/highScore.dat");
PlayerData data = new PlayerData();
data.playerName = playerName;
data.highScoreFinal = highScoreFinal;
bf.Serialize(file, data);
file.Close();
}
[Serializable]
class PlayerData
{
public int highScoreFinal;
public string playerName;
}
}
loadHighScore:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class loadHighScore : MonoBehaviour {
public static loadHighScore control;
int highScoreFinal;
string playerName;
public GameObject playerEntry;
void Start () {
LoadFromFile();
}
public void LoadFromFile()
{
if (File.Exists(Application.persistentDataPath + "/highScore.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/highScore.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
playerName = data.playerName;
highScoreFinal = data.highScoreFinal;
print(playerName);
print(highScoreFinal);
}
}
[Serializable]
class PlayerData
{
public int highScoreFinal;
public string playerName;
}
}
For this code I followed the Serialization Tutorial on Unitys YT channel, if anyone wonders.
I would be really helpful for someone steering me in the right direction of what's wrong here, cause I'm already looking at it for about 3 hours without being able to figure out whats wrong.