Home > OS >  How to find Correct path to save data in unity
How to find Correct path to save data in unity

Time:09-26

I've a game. I should save the game whenever end user exit. how to know where to save? because If I save the game to the under C://Users/.. path what happens if user uses Android or IOS? what is the solution for this problem?

CodePudding user response:

Use application data folder which changes depending on platform.

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

Read more about it here at source

CodePudding user response:

You should use 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);
    }
}

CodePudding user response:

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