Unity读取文件踩坑记

Unity读取文件一般用WWW(官方弃用接口),TextAsset,AssetBundle这三种方式。。。。
用C#的StreamReader方式读取,在调试的时候看似没毛病,打包出来就凉了,一点文字都不给显示。。。。。我。。。。。。。心里一万只。。。。。。
后来搜到了这篇文章:https://www.xuanyusong.com/archives/1069
才知道是路径出问题,打包出来还是区分一下平台路径
用Application.dataPath在安卓平台是绝对读取不到文件的。

#if UNITY_EDITOR
		string filepath = Application.dataPath +"/xxx.txt"; 
#elif UNITY_IPHONE
	  string filepath = Application.dataPath +"/xxx.txt";
 
#elif UNITY_ANDROID
	  string filepath = "jar:file://" + Application.dataPath + "/xxx.txt";
#endif

奇怪的是这样写打包成apk就报错,打不出来。
所以用下面的写法

 if (Application.platform == RuntimePlatform.Android)
{
   path = "jar:" + Application.dataPath + "!/assets";
}
if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor)
{
    path = Application.streamingAssetsPath;
}
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
   path = Application.dataPath + "/Raw";
}

打包出来的apk依旧读取不到文件内容。。。呃。。。T.T
最后还是用了TextAsset和AssetBundle。。。。

你可能感兴趣的:(Unity)