Unity. Android. Save files disappears after updating an App

若如初见. 提交于 2019-12-02 00:33:53

EDIT: Depending on your needs you may want to change the order of the potential directories and even favor external storage. If so please look at @LoungeKatt answer.

If you don't want to use the PlayerPrefs (which is I think the most robust available solution), you can always write directly into the user device.

WARNING: keep in mind doing it this way is far from a perfect solution ! The user can delete and edit the files you save and this is more of a workaround than a real answer.

Anyway, since the internal files directory paths changes from one Android device to another, you can use a small script to find it :

public static string GetAndroidInternalFilesDir()
{
    string[] potentialDirectories = new string[]
    {
        "/mnt/sdcard",
        "/sdcard",
        "/storage/sdcard0",
        "/storage/sdcard1"
    };

    if(Application.platform == RuntimePlatform.Android)
    {
        for(int i = 0; i < potentialDirectories.Length; i++)
        {
            if(Directory.Exists(potentialDirectories[i]))
            {
                return potentialDirectories[i];
            }
        }
    }
    return "";
}

Hope this helps,

Samsung and many other Android devices use a serial number as the mount point for external sdcards. Building on @Kardux's (original) answer for internal storage, the following will favor external storage (without a specific directory), then search for the internal sdcard as a fallback.

public static string GetAndroidInternalFilesDir()
{
    string[] potentialDirectories = new string[]
    {
        "/storage",
        "/sdcard",
        "/storage/emulated/0",
        "/mnt/sdcard",
        "/storage/sdcard0",
        "/storage/sdcard1"
    };

    if(Application.platform == RuntimePlatform.Android)
    {
        for(int i = 0; i < potentialDirectories.Length; i++)
        {
            if(Directory.Exists(potentialDirectories[i]))
            {
                return potentialDirectories[i];
            }
        }
    }
    return "";
}

Note: This assumes the external storage directory appears first in a directory list. It then prioritizes the attempts to access storage by likelihood of success and adds /storage/emulated/0, which many devices can access when unable to access /sdcard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!