Я хочу сохранить данные своей игры в файл после запуска игры, а затем после закрытия/начала игры я хочу загрузить данные из этого файла. Я попытался использовать решение this, но когда я начинаю, а затем останавливаю моделирование, я не вижу файл indicatorsInfo.dat
, но Debug.Log()
говорит, что он существует. В любом случае, это не загружает данные, что не так?Не удается сохранить данные в файл, а затем загрузить его в Unity3d
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GAMEMANAGERFileIO : MonoBehaviour
{
void OnEnable()
{
LoadFromFile();
SaveToFile();
}
void OnDisable()
{
SaveToFile();
}
public void SaveToFile()
{
GameObject gameManagerObject = GameObject.FindGameObjectWithTag("GAMEMANAGER");
GAMEMANAGER gameManager = gameManagerObject.GetComponent<GAMEMANAGER>();
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = File.Create(Application.persistentDataPath + "/indicatorsInfo.dat"); // open file
IndicatorsInfo indicatorsInfo = new IndicatorsInfo();
// Initialise data of the class IndicatorsInfo
//...
// save data to the file. Serialize([to where we want to save], [what we want to save])
binaryFormatter.Serialize(fileStream, indicatorsInfo);
========== EDIT 1 ======================================================
File.WriteAllText("C:/Users/dima/Desktop/exampleSaveData.txt",
indicatorsInfo.walkSpeedTemfFile.ToString() + ", " +
indicatorsInfo.runSpeedTemfFile + ", " +
indicatorsInfo.jumpForceTemfFile + ", " +
indicatorsInfo.enduranceTemfFile);
========================================================================
fileStream.Close();
Debug.Log("saved"); // this works
}
public void LoadFromFile()
{
// check if file exisits before we will try to open it
if(File.Exists(Application.persistentDataPath + "/indicatorsInfo.dat"))
{
GameObject gameManagerObject = GameObject.FindGameObjectWithTag("GAMEMANAGER");
GAMEMANAGER gameManager = gameManagerObject.GetComponent<GAMEMANAGER>();
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = File.Open(Application.persistentDataPath + "/indicatorsInfo.dat", FileMode.Open); // open file
IndicatorsInfo indicatorsInfo = (IndicatorsInfo)binaryFormatter.Deserialize(fileStream); // read from file
fileStream.Close(); // close file
// Initialise local data with values from the class IndicatorsInfo
//...
========== EDIT 1 ======================================================
File.ReadAllText("C:/Users/dima/Desktop/exampleSaveData.txt");
========================================================================
}
}
}
// clear class with data, which we will store to file
[Serializable]
class IndicatorsInfo
{
//...
}
EDIT 1
Я добавил File.WriteAllText()
и File.ReadAllText()
. Но у меня есть 2 проблемы:
- Мне нужно создать файл txt самостоятельно, прежде чем я смогу его сохранить;
- Я могу сохранить данные в файл (значения 4 переменных), но я не могу его загрузить.
Но я использую 'Application.persistentDataPath',' binaryFormatter.Serialize (,) 'писать и' binaryFormatter.Deserialize() 'для чтения. Я не использую 'File.WriteAllText (f, t)', 'File.ReadAllText (f)'. Это причина, почему она не работает? – dima
binaryFormatter.Serialize/Deserialize не сохраняют данные, они сериализуют их, что превращает их в двоичную форму. – Everts