【Unity学习】打包安卓平台读取StreamingAssets文件夹内容以及写入PersistentDataPath并读取

直接上代码

using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;

public class Test
{
    public string description;

    public Test(string description)
    {
        this.description = description;
    }

    public Test()
    {

    }
}

public class SaveManager : MonoBehaviour
{
    public TMP_InputField tMP_InputField;
    public TextMeshProUGUI textMeshProUGUI;
    public string path;
    private Test test;

    private void Awake()
    {
        path = "test.txt";
        tMP_InputField.onEndEdit.AddListener(SaveData);
        test = new Test();
    }

    void Start()
    {
        if (File.Exists(Path.Combine(Application.persistentDataPath, path)))
        {
            JsonUtility.FromJsonOverwrite(GetData(Path.Combine(Application.persistentDataPath, path)), test);
            textMeshProUGUI.text = test.description;
        }
        else
        {
            JsonUtility.FromJsonOverwrite(GetData(Path.Combine(Application.streamingAssetsPath, path)), test);
            textMeshProUGUI.text = test.description;
        }

    }

    private void SaveData(string text)
    {
        if (!File.Exists(Path.Combine(Application.persistentDataPath, path)))
        {
            using (var st = File.CreateText(Path.Combine(Application.persistentDataPath, path)))
            {
                st.Write(JsonUtility.ToJson(new Test(text)));
                st.Close();
            }
        }
        else
        {
            File.WriteAllText(Path.Combine(Application.persistentDataPath, path), JsonUtility.ToJson(new Test(text)));
        }

        JsonUtility.FromJsonOverwrite(GetData(Path.Combine(Application.persistentDataPath, path)), test);
        textMeshProUGUI.text = test.description;
    }

    private string GetData(string path)
    {
        var url = new System.Uri(path);
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.SendWebRequest();
        if (request.result == UnityWebRequest.Result.ConnectionError)
        {
            return "";
        }
        else
        {
            while (true)
            {
                if (request.downloadHandler.isDone)
                {
                    return request.downloadHandler.text;
                }
            }
        }
    }
}

在这里插入图片描述
打包到安卓平台没有问题。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值