- Home /
This question was
closed Aug 04, 2020 at 11:50 AM by
gf457767 for the following reason:
This is outdated for me now
Question by
gf457767 · May 23, 2020 at 01:19 PM ·
save datasaveloadloading file
Save/Load System not working
I tried to create a save/load system for my project,but is not working.I put this function:Debug.Log("Data has been saved"); to tell me if when I press the save button the data I am really saving the data,and the in the console the message:Data has been saved appears,but when I click the load button the message(I created this message using the debug.log):Data has been loaded appears,but it is not loading(Data that I want to be saved and loaded are the player's level and the position of the player). Here are my codes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerData {
public int level;
public float[] position;
public PlayerData (DataSaved player)
{
level = player.level;
position = new float[3];
position[0] = player.transform.position.x;
position[1] = player.transform.position.y;
position[2] = player.transform.position.z;
}
}
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem {
public static void SavePlayer (DataSaved player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/SavedData.dat";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static PlayerData LoadPlayer ()
{
string path = Application.persistentDataPath + "/SavedData.dat";
if(File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
} else
{
Debug.LogError("Saved file not found in " + path);
return null;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DataSaved : MonoBehaviour
{
public int level = 5;
public Text text1;
public Text text2;
public Text text3;
public Text text4;
public void SavePlayer()
{
SaveSystem.SavePlayer(this);
string timeUS = System.DateTime.UtcNow.ToLocalTime().ToString("M/d/yy hh:mm:ss tt");
text1.text = timeUS;
text2.text = timeUS;
text3.text = timeUS;
text4.text = timeUS;
Debug.Log("Data has been saved");
}
public void LoadPlayer()
{
PlayerData data = SaveSystem.LoadPlayer();
level = data.level;
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
transform.position = position;
Debug.Log("Data has been loaded");
}
}
Comment