【问题标题】:Can't save data to file and then load it in Unity3d无法将数据保存到文件然后在 Unity3d 中加载
【发布时间】:2016-03-20 05:48:39
【问题描述】:

我想在启动游戏后将我的游戏数据保存到文件中,然后在再次关闭/启动游戏后我想从该文件加载数据。我尝试使用this 解决方案,但是当我开始然后停止模拟时,我看不到文件indicatorsInfo.dat,但Debug.Log() 说它存在。反正它不加载数据,怎么回事?

    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
    {
        //...
    }

编辑 1

我添加了File.WriteAllText()File.ReadAllText()。但我有两个问题:

  1. 我需要自己创建txt文件才能保存到它;
  2. 我可以将数据保存到文件(4 个变量的值),但我无法加载它。

【问题讨论】:

标签: c# file unity3d fileinputstream fileoutputstream


【解决方案1】:

在 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);

注意…………

// 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

【讨论】:

  • 但是我使用Application.persistentDataPath, binaryFormatter.Serialize(,) 来写和binaryFormatter.Deserialize() 来读。我不使用File.WriteAllText(f,t)File.ReadAllText(f)。这是它不起作用的原因吗?
  • binaryFormatter.Serialize/Deserialize 不是保存数据,而是对它们进行序列化,即将它们转换为二进制形式。
  • @Everts 请注意,BinaryFormatter 可以直接序列化和反序列化 FileStream (File.Open(..)),其优点是不必先将整个文件内容加载到内存中。
  • 虽然,@DimaKozyr 今年最近你应该停止使用BinaryFormatterat all!
  • 这绝对是正确的,但对于初学者来说,重要的是要意识到在 Unity 环境中可能会出现这种情况的情况非常、非常、非常少。 Unity 不断加载兆字节级的图像(仅作为示例)。加载几千个项目的小文本文件,担心流是非常误导的。请注意,另一方面,如果由于某种原因您确实有一些文本数据是数以千万计的项目,那么您绝对应该使用 mysql。
猜你喜欢
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多