【Unity】数据持久化及方法


一、Unity常见路径以及文件夹

1.1 常见路径

Unity中包含很多特殊文件夹以及路径。

属性名 作用
Application.dataPath 此属性用于返回程序的数据文件所在文件夹的路径,例如Editor中的Assets。
Application.streamingAssetsPath 此属性用于返回流数据的缓存目录,返回路径为相对路径,适合设置一些外部数据文件的路径。该路径下的文件是只读的。
Application.persistentDataPath 此属性用于返回一个持久化数据存储目录的路径,可以在此路径下存储一些持久化的数据文件。
Application.temporaryCachePath 此属性用于返回一个临时数据的缓存目录。
Android平台
属性名 路径
Application.dataPath /data/app/xxx.xxx.xxx.apk
Application.streamingAssetsPath jar:file:///data/app/xxx.xxx.xxx.apk/!/assets
Application.persistentDataPath /data/data/xxx.xxx.xxx/files
Application.temporaryCachePath /data/data/xxx.xxx.xxx/cache
IOS平台
属性名 路径
Application.dataPath Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data
Application.streamingAssetsPath Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data/Raw
Application.persistentDataPath Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Documents
Application.temporaryCachePath /data/data/xxx.xxx.xxx/Library/Cache

注:Application.dataPath该路径在移动端没有访问权限!

1.2 文件夹

Resources

是一个Unity3D的保留文件夹,里面的内容在打包时会被无条件的打到发布包中

它的特点简单总结就是:

  1. 只读,即不能动态修改,所以动态更新的资源不要放在其中
  2. 会将文件夹内的资源打包集成到.asset文件里面,因此可以放入一些Prefab,因为Prefab打包时会自动过滤不需要的资源
  3. 主线程加载,资源读取使用Resources.Load()
StreamingAssets

和Resources类似,同样是一个只读的Unity3D的保留文件夹

不同的是Resources文件夹中的内容在打包时会被压缩和加密

而StreamingAssets文件夹中的内容则会原封不动的打入包中,因此主要用来存放一些二进制文件

  1. 同样只读不可写。
  2. 主要用来存放二进制文件。
  3. 只能用WWW类来下载,在Unity2018以后使用UnityWebRequest类。

实际代码:

  • WWW方法(高版本已弃用)
IEnumerator LoadStreamingAssetsByWWW()
{
   
	string filePath = Application.streamingAssetsPath + "/test.txt";
	WWW www = new WWW(filePath);
	yield return www;
	_result = www.text;
}
  • UnityWebRequest方法
IEnumerator LoadStreamingAssetsByUnityWebRequest()
{
   
	string filePath = Application.streamingAssetsPath + "/test.txt";
	UnityWebRequest webRequest = UnityWebRequest.Get(filePath);
	yield return webRequest.SendWebRequest();
	
	//异常处理
	if (webRequest.isHttpError || webRequest.isNetworkError)
	{
   
		Debugger.Log(webRequest.error);
	}
	// webRequest 就是最后获取到的文件数据
	// webRequest.downloadHandler.data 获取二进制数据
}

注:这段代码编写完成之后,在Mac或者编辑器里测试,无法输出内容。Editor和IOS在读取本地文件的时候,地址需要加一个file://。

string filePath = "file://" + Application.streamingAssetsPath 
  • 5
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值