Hey
I need help in saving player data in a file. I have developed a game consisting of 3 different levels.
It stores game statistics i.e. gems and fruits player has, health and lives, the overall progress of player, and settings i.e. mute music and volume, etc. I have already done this using player.pref. It is working fine.
as it is not that much sure and professional to store player statistics in player preferences so now I want to save this in a binary file.
I need your kind help -
-
It saves data in the scene i.e. “Level 3” while playing. but when I quit the game and replay the game
data is not loaded in scene “Main Menu”. -
What data to store in player pref and when to use file datastorage?
Here is the code:
public class SaveSystem : MonoBehaviour
{
public static SaveSystem instance;
public bool hasLoaded;
string path;
private void Awake()
{
path = Application.persistentDataPath + "/player.dev";
if (!File.Exists(path))
SavePlayer();
if (instance != null)
{
Destroy(gameObject);
return;
}
else
{
instance = this;
LoadPlayer();
DontDestroyOnLoad(gameObject);
}
if(hasLoaded)
{
}
}
public PlayerData playerData;
private void Start()
{
// playerData = new PlayerData();
}
public void SavePlayer()
{
BinaryFormatter formatter = new BinaryFormatter();
Debug.Log(path + " Path");
FileStream stream;
//var serliaizer = new XmlSerializer(typeof(PlayerData));
stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData();
formatter.Serialize(stream, data);
stream.Close();
Debug.Log("Data saved");
}
public PlayerData LoadPlayer()
{
//string path = Application.persistentDataPath + "/player.dev";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
//XmlSerializer serliaizer = new XmlSerializer(typeof(PlayerData));
FileStream stream = new FileStream(path, FileMode.Open);
playerData = formatter.Deserialize(stream) as PlayerData;
Debug.Log("Load ");
hasLoaded = true;
stream.Close();
return playerData;
}
else
{
Debug.LogError("Save file not found in " + path);
return null;
}
}
void DeleteData()
{
// string path = Application.persistentDataPath + "/player.dev";
if (File.Exists(path))
{
File.Delete(path);
}
}
}
[System.Serializable]
public class PlayerData
{
public string level;
public string difficultyLevel;
public int gemPlayerHas;
public int cherryPlayerHas;
public int health;
public int lives;
public int numOfArrows;
public int avatarSelected;
public float[] lastCheckPointPos;
public PlayerData( )
{
lastCheckPointPos = new float[2];
lives = PlayerMovement.lives;
health = PlayerMovement.currentHealth;
level = MainMenu.currentLevel;
difficultyLevel = MainMenu.difficultyLevel;
gemPlayerHas = GiftData.gemCount;
cherryPlayerHas = GiftData.cherryCount;
//lastCheckPointPos = GameMaster.
}
}