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访问,无法使用例如 Directory.GetFiles的方式访问,可以使用File.Exists()来判断文件是否存在

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

}

  • 9
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Unity WebGL是一种用于在Web浏览器中运行Unity游戏的技术。由于WebGL的限制,Unity WebGL无法直接访问本地存储。但是,你可以使用PlayerPrefs和JsonUtility来实现在Unity WebGL中进行本地存储数据的功能。 PlayerPrefs是Unity提供的一个用于存储和访问玩家偏好设置的类。它可以用来保存和读取各种数据类型,包括整数、浮点数、字符串等。 JsonUtility是Unity提供的一个用于序列化和反序列化JSON数据的类。你可以使用JsonUtility将数据转换为JSON格式,并将其保存到PlayerPrefs中,然后在需要的时候再从PlayerPrefs中读取并反序列化为对象。 以下是一个示例代码,演示了如何在Unity WebGL中使用PlayerPrefs和JsonUtility实现本地存储数据的功能: ```csharp using UnityEngine; public class LocalStorageExample : MonoBehaviour { // 定义一个数据类 [System.Serializable] public class MyData { public int score; public string playerName; } void Start() { // 创建一个数据对象 MyData data = new MyData(); data.score = 100; data.playerName = "Player1"; // 将数据对象转换为JSON格式 string json = JsonUtility.ToJson(data); // 将JSON数据保存到PlayerPrefs中 PlayerPrefs.SetString("myData", json); // 从PlayerPrefs中读取JSON数据 string savedJson = PlayerPrefs.GetString("myData"); // 将JSON数据反序列化为数据对象 MyData savedData = JsonUtility.FromJson<MyData>(savedJson); // 输出读取到的数据 Debug.Log("Score: " + savedData.score); Debug.Log("Player Name: " + savedData.playerName); } } ``` 在上述示例中,我们定义了一个名为MyData的数据类,它包含一个整数类型的score和一个字符串类型的playerName。我们创建了一个MyData对象,并将其转换为JSON格式的字符串。然后,我们将JSON数据保存到PlayerPrefs中,并从PlayerPrefs中读取并反序列化为MyData对象。最后,我们输出读取到的数据。 请注意,由于Unity WebGL的限制,PlayerPrefs只能在WebGL的本地存储中保存少量数据。如果你需要保存大量数据,你可能需要考虑使用其他方法,如将数据发送到服务器进行存储
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值