2016-03-19 12 views
0

Я хочу сохранить данные своей игры в файл после запуска игры, а затем после закрытия/начала игры я хочу загрузить данные из этого файла. Я попытался использовать решение this, но когда я начинаю, а затем останавливаю моделирование, я не вижу файл indicatorsInfo.dat, но Debug.Log() говорит, что он существует. В любом случае, это не загружает данные, что не так?Не удается сохранить данные в файл, а затем загрузить его в Unity3d

enter image description here

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 проблемы:

  1. Мне нужно создать файл txt самостоятельно, прежде чем я смогу его сохранить;
  2. Я могу сохранить данные в файл (значения 4 переменных), но я не могу его загрузить.

enter image description here

ответ

3

Это невероятно легко писать и читать файлы в Unity.

// IO crib sheet.. 
// filePath = Application.persistentDataPath+"/"+fileName; 
// check if file exists System.IO.File.Exists(f) 
// write to file File.WriteAllText(f,t) 
// delete the file if needed File.Delete(f) 
// read from a file File.ReadAllText(f) 

это все, что в этом есть.

string currentText = File.ReadAllText(filePath); 

ПРИМЕЧАНИЕ WELL ...........

// filePath = Application.persistentDataPath+"/"+fileName; 
// YOU MUST USE "Application.persistentDataPath" 
// YOU CANNOT USE ANYTHING ELSE 
// NOTHING OTHER THAN "Application.persistentDataPath" WORKS 
// ALL OTHER OPTIONS FAIL ON ALL PLATFORMS 
// YOU CAN >ONLY< USE Application.persistentDataPath IN UNITY 
+0

Но я использую 'Application.persistentDataPath',' binaryFormatter.Serialize (,) 'писать и' binaryFormatter.Deserialize() 'для чтения. Я не использую 'File.WriteAllText (f, t)', 'File.ReadAllText (f)'. Это причина, почему она не работает? – dima

+1

binaryFormatter.Serialize/Deserialize не сохраняют данные, они сериализуют их, что превращает их в двоичную форму. – Everts