【问题标题】:How to find Correct path to save data in unity如何找到正确的路径以统一保存数据
【发布时间】:2021-09-25 14:52:07
【问题描述】:

我有一个游戏。每当最终用户退出时,我都应该保存游戏。 如何知道在哪里保存?因为如果我将游戏保存到C://Users/.. 路径下,如果用户使用 AndroidIOS 会发生什么?这个问题的解决方法是什么?

【问题讨论】:

    标签: c# unity3d save


    【解决方案1】:

    你应该使用Application.persistentDataPathmethod

    这个值是一个目录路径,你可以在其中存储你想要的数据 在运行之间保持。当您在 iOS 和 Android 上发布时, persistentDataPath 指向设备上的公共目录。文件 应用更新不会删除此位置中的内容。文件仍然可以 被用户直接删除。

    当您构建 Unity 应用程序时,会生成一个 GUID,即 基于捆绑标识符。此 GUID 是 持久数据路径。如果您将来保留相同的 Bundle Identifier 版本中,应用程序在每个版本上都保持访问相同的位置 更新。

    using UnityEngine;
    
    public class Info : MonoBehaviour
    {
        void Start()
        {
            Debug.Log(Application.persistentDataPath);
        }
    }
    

    【讨论】:

      【解决方案2】:

      使用根据平台变化的应用程序数据文件夹。

      //Attach this script to a GameObject
      //This script outputs the Application’s path to the Console
      //Run this on the target device to find the application data path for the platform
      using UnityEngine;
      
      public class Example : MonoBehaviour
      {
          string m_Path;
      
          void Start()
          {
              //Get the path of the Game data folder
              m_Path = Application.dataPath;
      
              //Output the Game data path to the console
              Debug.Log("dataPath : " + m_Path);
          }
      }
      

      阅读更多关于它的信息here at source

      【讨论】:

      • 在 Android 上它直接指向 APK。此路径是只读的,您将无法对其进行写入。
      【解决方案3】:
      There is structure or class and on it base will be better to creating objects and writing its in file.
      
      [System.Serialisable]
      public class AAA{
          public string Name = "";
          public int iNum = 0;
          public double dNum = 0.0;
          public float fNum = 0f;
          int[] array;
          // Here may be any types of datas and arrays and lists too.
      }
      
      
      AAA aaa = new AAA(); // Creating object which will be serialis of datas.
      // Initialisation our object:
      aaa.Name = "sdfsf";
      aaa.iNum = 100; 
      
      string path = "Record.txt"
      #if UNITY_ANDROID && !UNITY_EDITOR
          path = Path.Combine(Application.persistentDataPath, path);
      #else
          path = Path.Combine(Application.dataPath, path);
      #endif
      
      // Writing datas in file - format JSON:
      string toJson = JsonUtility.ToJson(aaa, true);
      File.WriteAllText(path, toJson);
      
      // reading datas from file with JSON architecture and serialis.. it in object:
      string fromjson = File.ReadAllText(path);
      AAA result = JsonUtility.FromJson<AAA>(fromjson);
      

      【讨论】:

        猜你喜欢
        • 2019-11-26
        • 1970-01-01
        • 2021-10-19
        • 2023-03-09
        • 2014-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        相关资源
        最近更新 更多