Unity打包安卓如何存储本地游戏数据?

一、前言

平时项目得数据文件文件一般都使用Resources.Load或者Application.streamingAssetsPath这两中方式读取,但是项目打包成Android或IOS时这些路径获取方式就不能用原方法了。下面讲一下打包安卓后这两个文件夹的文件路径、读取权限及注意事项。

二、打包安卓后路径

1、Resources文件夹

打包安卓后可使用Resources.Load<T>("文件名");获取文件数据.

注意:

1.在安卓中只能读不能写

2.文件名不能加后缀名

2.StreamingAssets文件夹

打包安卓后路径为:"jar:file://" + Application.dataPath + "!/assets/" +文件名.后缀名 这一串路径等同于Application.streamingAssetsPath+"/"+文件名.后缀名 

注意:

1.官方路径"jar:file://" + Application.dataPath + "!/assets"中 "!/assets"是少了一个 " /" 的,要注意在文件名前加一个 " /"

2.在安卓中只能读不能写

3.获取数据只能使用WWW或UnityWebRequest访问

3.文件要加后缀名

3.Application.persistentDataPath 路径(推荐使用)

这个文件路径在安卓中比较特殊,他是在游戏运行的时候使用代码来创建才行。

注意:

1.该文件需要在游戏运行时使用代码创建

2.在安卓中游戏运行时可以进行读取操作

3.获取修改数据可以使用File类、WWW或UnityWebRequest访问

4.文件要加后缀名

三、实际引用

在做之前推荐大家一个手机端的错误信息获取插件IngameDebugConsole,可以直接在商城搜索下载免费的超级好用。Ctrl+9快捷键可以打开商城。

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6KKr5Luj56CB5oqY56Oo55qE54uX5a2Q,size_20,color_FFFFFF,t_70,g_se,x_16

 导入后,拖入预设即可,运行后会自动获取错误和debug等信息。

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6KKr5Luj56CB5oqY56Oo55qE54uX5a2Q,size_12,color_FFFFFF,t_70,g_se,x_16

 演示:运行会自动出现。

e638e349e09e4f3280eefc2961e06f73.gif

 接下来步入正题,先说一下思路,我们在PC端测试时使用StreamingAssets文件夹下的Txt文件存储Json游戏数据,在android中的话,分为3步:

(1)游戏运行先获取StreamingAssets下的数据,

(2)获取到后判断persistentDataPath是否有这个Txt文件,没有创建一个Txt文件

(3)创建完毕,将读取的数据存储。

好的知道思路后我们开始做吧。

 1.第一步

先在StreamingAssets创建一个test.txt文件,用于存放游戏json数据

{
"username":"张三",
"password":123456
}

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6KKr5Luj56CB5oqY56Oo55qE54uX5a2Q,size_6,color_FFFFFF,t_70,g_se,x_16

2.第二步

判断我们程序运行是在PC还是Android端,获取StreamingAssets下test.Txt的数据,判断persistentDataPath是否有这个test.Txt文件,没有的话创建一个test.Txt文件并将数据写入新建文件中。

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using System;

public class Test : MonoBehaviour
{

    void Start()
    {
        //CreatPersistentDataData("Test.txt");
        StartCoroutine("GetData", "Test.txt");

    }

    #region 创建persistentDataPath文件夹

    IEnumerator CreatPersistentDataData(string fileName)
    {
        string fromPath = "";

        if (Application.platform == RuntimePlatform.Android)
            fromPath = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
        else
            fromPath = Application.streamingAssetsPath + "/" + fileName;

       #region 使用WWW方法
        //WWW www = new WWW(fromPath);
        //yield return www;
        //if (www.isDone)
        //{
        //    if (!File.Exists(Application.persistentDataPath + "/" + fileName))
        //    {
        //        FileStream fs = File.Create(Application.persistentDataPath + "/" + fileName);
        //        fs.Close();

        //        File.WriteAllBytes(Application.persistentDataPath + "/" + fileName, www.bytes);
        //    }

        //    stagePropertyData = JsonMapper.ToObject<StagePropertyData>(GetTextForStreamingAssets("StagePropertyData.txt"));//初始化数据

        //    //播放当前背景音乐
        //    SetPanel.GetInstance().SetBgMusic(StagePropertyData.bgmusicindex);

        //    //道具数量刷新
        //    RefreshStagePropertyNumber(moneyStagePropertyTxt, timeStagePropertyTxt, findStagePropertyTxt);
        //}
        #endregion

        #region 使用UnityWebRequest方法
        UnityWebRequest request = UnityWebRequest.Get(fromPath);
        yield return request.SendWebRequest();

        if (request.isHttpError || request.isNetworkError)
            Debug.Log(request.error);
        else 
        {
            //Debug.Log(request.downloadHandler.text);
            if (!File.Exists(Application.persistentDataPath + "/" + fileName))
            {
                FileStream fs = File.Create(Application.persistentDataPath + "/" + fileName);
                fs.Close();

                File.WriteAllBytes(Application.persistentDataPath + "/" + fileName, request.downloadHandler.data);
            }

            stagePropertyData = JsonMapper.ToObject<StagePropertyData>(GetTextForStreamingAssets("StagePropertyData.txt"));//初始化数据

            //播放当前背景音乐
            SetPanel.GetInstance().SetBgMusic(StagePropertyData.bgmusicindex);

            //道具数量刷新
            RefreshStagePropertyNumber(moneyStagePropertyTxt, timeStagePropertyTxt, findStagePropertyTxt);
        }
        #endregion
    }

    #endregion


}

3.第三步

根据不同平台获取Txt文件路径,并读取数据转换成json类。

[Serializable] //一定要序列化
public class TestData 
{
    //字段名字要与json对应
    public string username; 
    public int password;
}

#region 获取Json数据文件
    TestData testData;//创建存储json数据类

    string GetTextForStreamingAssets(string fileName)
    {
        string jsonPath;
        if (Application.platform == RuntimePlatform.Android)
            jsonPath = Application.persistentDataPath + "/" + fileName;
        else
            jsonPath = Application.streamingAssetsPath + "/" + fileName;

        string data = File.ReadAllText(jsonPath);
        //Debug.Log("获取Json数据文件: " + data);
        return data;
    }

    #endregion


4.修改数据

#region 存储json数据
    public void SaveJsonData(string fileName)
    {
        string jsonPath;

        if (Application.platform == RuntimePlatform.Android)
            jsonPath = Application.persistentDataPath + "/" + fileName; //安卓存储
        else
            jsonPath = Application.streamingAssetsPath + "/" + fileName; //pc存储

        if (File.Exists(jsonPath))
        {
            byte[] byteData = System.Text.Encoding.Default.GetBytes(JsonUtility.ToJson(testData, true));
            File.WriteAllBytes(jsonPath, byteData);
        }
    }
    #endregion

 最终整合:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using System;

[Serializable] //一定要序列化
public class TestData 
{
    //字段名字要与json对应
    public string username; 
    public int password;
}

public class Test : MonoBehaviour
{

    void Start()
    {
        StartCoroutine("CreatPersistentDataData", "Test.txt"); //开启协程
    }

    #region 创建persistentDataPath文件夹
    TestData testData;//创建存储json数据类
    IEnumerator CreatPersistentDataData(string fileName)
    {
        string fromPath = "";

        if (Application.platform == RuntimePlatform.Android)
            fromPath = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
        else
            fromPath = Application.streamingAssetsPath + "/" + fileName;

        WWW www = new WWW(fromPath);
        yield return www;
        if (www.isDone)
        {
            if (!File.Exists(Application.persistentDataPath + "/" + fileName))
            {
                FileStream fs = File.Create(Application.persistentDataPath + "/" + fileName);
                fs.Close();

                File.WriteAllBytes(Application.persistentDataPath + "/" + fileName, www.bytes);
            }

            testData = JsonUtility.FromJson<TestData>(GetTextForStreamingAssets(fileName));
        }
    }

    #endregion


    #region 获取Json数据文件

    string GetTextForStreamingAssets(string fileName)
    {
        string jsonPath;
        if (Application.platform == RuntimePlatform.Android)
            jsonPath = Application.persistentDataPath + "/" + fileName;
        else
            jsonPath = Application.streamingAssetsPath + "/" + fileName;

        string data = File.ReadAllText(jsonPath);
        //Debug.Log("获取Json数据文件: " + data);
        return data;
    }

    #endregion


    #region 存储json数据
    public void SaveJsonData(string fileName)
    {
        string jsonPath;

        if (Application.platform == RuntimePlatform.Android)
            jsonPath = Application.persistentDataPath + "/" + fileName; //安卓存储
        else
            jsonPath = Application.streamingAssetsPath + "/" + fileName; //pc存储

        if (File.Exists(jsonPath))
        {
            byte[] byteData = System.Text.Encoding.Default.GetBytes(JsonUtility.ToJson(testData, true));
            File.WriteAllBytes(jsonPath, byteData);
        }
    }
    #endregion

}

猜你喜欢

转载自blog.csdn.net/qq_42345116/article/details/123034327