在游戏运行期间,只有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);
}
}