0

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?

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

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.

enter image description here

Amazing User
  • 3,473
  • 10
  • 36
  • 75

1 Answers1

2

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
Fattie
  • 27,874
  • 70
  • 431
  • 719
  • But I use `Application.persistentDataPath`, `binaryFormatter.Serialize(,)` to write and `binaryFormatter.Deserialize()` to read. I don't use `File.WriteAllText(f,t)`, `File.ReadAllText(f)`. Is it a reason why it don't work? – Amazing User Mar 19 '16 at 16:46
  • 1
    binaryFormatter.Serialize/Deserialize are not saving data, they are serializing them, that is turning them into binary form. – Everts Mar 19 '16 at 19:40
  • @Everts note though that the BinaryFormatter can directly serialize into and deserialize from a `FileStream` (`File.Open(..)`) which has the advantage that not the entire file content has to be load into memory first. – derHugo Feb 20 '21 at 16:09
  • Though, @DimaKozyr latest this year you should **stop using `BinaryFormatter` [at all!](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter.serialize)** – derHugo Feb 20 '21 at 16:11
  • that's absolutely true but it's important for beginners to realize there are very, very, very few situations where that could possibly arise in the Unity milieu. Unity is loading megabyte-scale images (just for example) constantly. loading a tiny text file of a few thousand items, would be very misguided to worry about streams. note that on the other end if for some reason you DID have some text data being 10s of millions of items, you should absolutely be using mysql anyway. – Fattie Feb 20 '21 at 16:11