Can't save data to file and then load it in Unity3d

不问归期 提交于 2019-12-12 03:26:51

问题


I want to save data of my game to file after starting the game, then after close/start game again I want to load data from that file. I tried to use this solution, but when I start and then stop simulation, I don't see file indicatorsInfo.dat, but Debug.Log() says, that it exists. Anyway it don't load the data, what is wrong?

    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

I've added File.WriteAllText() and File.ReadAllText(). But I have 2 problems:

  1. I need to create txt file by myself before I could save to it;
  2. I can save data to file (values of 4 variables), but I can't load it.


回答1:


It's incredibly easy to write and read files in 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)

that's all there is to it.

string currentText = File.ReadAllText(filePath);

NOTE 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


来源:https://stackoverflow.com/questions/36103459/cant-save-data-to-file-and-then-load-it-in-unity3d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!