Unity 3D 运行期间读写文本

在游戏运行期间,只有Resources 和 StreamingAssets 目录具有读取权限,其中Resources用来读取游戏资源,而StreamingAssets可使用File类来读取文件(除个别平台),但是都是只读的,并不能写。

只有Application.persistentDataPath 目录是可读 可写的。

using System;
using System.IO;
using System.Text;
using UnityEngine;

public class ReadWriteTextWhenRunningMyTools : MonoBehaviour
{
    //--可读不可写
    private string m_ResourcesTxt = string.Empty;
    //--可读不可写
    private string m_StreamingAssetsTxt = string.Empty;
    //--可读可写
    private string m_PersistentDataTxt = string.Empty;

    private void Start()
    {
        m_ResourcesTxt = Resources.Load<TextAsset>("MyText/test").text;
        //Debug.Log(m_ResourcesTxt);
        m_StreamingAssetsTxt = File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "MyText/test.txt"), Encoding.Default);
        //Debug.Log(m_StreamingAssetsTxt);
    }

    private void OnGUI()
    {
        GUILayout.Label(string.Format("<size=50>{0}</size>", m_ResourcesTxt));
        GUILayout.Label(string.Format("<size=50>{0}</size>", m_StreamingAssetsTxt));
        GUILayout.Label(string.Format("<size=50>{0}</size>", m_PersistentDataTxt));

        if (GUILayout.Button("<size=50>写入并读取时间按钮</size>"))
        {
            string path = Path.Combine(Application.persistentDataPath, "test.txt");
            File.WriteAllText(path, string.Format("我是persistentDataPath路径 可读可写 :{0}", DateTime.Now.ToString()));
            m_PersistentDataTxt = File.ReadAllText(path);
        }
    }
}

有时中文是乱码,可以加上Encoding.Default。

打包运行:

PersistentDataPath在开发中比较难找,写个脚本快速打开。

using UnityEditor;
using UnityEngine;

public class OpenPersistentDataPathMyTools
{
    [MenuItem("Tools/OpenPersistentDataPath", false)]
    static void OpenPersistentDataPath()
    {
        EditorUtility.RevealInFinder(Application.persistentDataPath);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值