如何找到统一保存数据的正确路径

How to find Correct path to save data in unity

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

使用因平台而异的应用程序数据文件夹。

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

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

你应该使用 Application.persistentDataPath method.

This value is a directory path where you can store data that you want to be kept between runs. When you publish on iOS and Android, persistentDataPath points to a public directory on the device. Files in this location are not erased by app updates. The files can still be erased by users directly.

When you build the Unity application, a GUID is generated that is based on the Bundle Identifier. This GUID is part of persistentDataPath. If you keep the same Bundle Identifier in future versions, the application keeps accessing the same location on every update.

using UnityEngine;

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