通过WWW获取资源流时,Windows本地的绝对路径前要添加"file://"
/// <summary>
/// WWW本地资源存放的路径(AssetBundle、xml、txt)
/// </summary>
public static string LocalResourceWWWPath
{
get
{
switch (Application.platform)
{
case RuntimePlatform.Android:
return string.Concat("file://", Application.persistentDataPath, ManifestName);
case RuntimePlatform.IPhonePlayer:
return string.Concat("file://", Application.persistentDataPath, ManifestName);
case RuntimePlatform.OSXEditor:
case RuntimePlatform.OSXPlayer:
case RuntimePlatform.WindowsEditor:
return string.Concat("file://", Application.persistentDataPath.Replace("/", "\\"), ManifestName.Replace("/", "\\"));
case RuntimePlatform.WindowsPlayer:
return string.Concat("file://", Application.persistentDataPath.Replace("/", "\\"), ManifestName.Replace("/", "\\"));
default:
return "";
}
}
}
/// <summary>
/// WWW初始资源存放的位置(第一次启动复制此路径中的资源到本地资源路径)
/// </summary>
public static string InitResourceWwwPath
{
get
{
switch (Application.platform)
{
case RuntimePlatform.Android:
return string.Concat(Application.streamingAssetsPath, "/", ManifestName, "/");
default:
return string.Concat("file://", Application.streamingAssetsPath, "/", ManifestName, "/");
}
}
}
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
注意下"/“同”\“的区别,Unity默认所有通过代码获取的路径都是采用”/",而windows系统则默认所有路径都是采用"\",对比上述代码跟安卓平台路径我们可以发现streamingAssetsPath路径默认已经添加上了jar:file://,所以在加载WWW路径时不用再手动添加,而persistentDataPath路径默认是没有添加的,所以在加载WWW路径时仍需要手动添加,其中"jar:"安卓系统会自动添加上.
主要区别:
1.通过IO类来进行文件的读取与写入,直接采用unity默认的路径是没有任何问题的,但是如果通过WWW来进行流的读取时,unity自身项目同读取的文件在一个盘符时,采用默认路径也没有问题,例如 Application.streamingAssetsPath 路径默认就在unity自身项目中,所以肯定跟unity自身项目一个盘符.
2.采用 Application.persistentDataPath时,此路径默认在windows系统的C盘,如果unity项目文件在其他盘符,此时直接通过 Application.persistentDataPath来进行文件流的读取就会出问题,必须把"/“替换成”\",这样才能实现不同盘符文件的访问,当然同一个盘符更能访问,或者项目文件也在C盘不用替换也能访问.
3.WWW路径不可以用IO来判断文件夹是否存在,下载的时候用WWW来进行下载,本地存储还是采用IO类.
注意:StreamingAssets目录中的内容安卓环境下可以通过WWW或者 AssetBundle.LoadFromFile()来进行加载,但是不能通过IO来进行读取,所以File.Exists()、Directory.Exists()、File.ReadAllText都是不能使用的,具体原因不明。需要注意的是unity2017之前的unity版本中在编辑器模式下以及苹果端Application.streamingAssetsPath前面还需要加上"file: //".示例如下:
#if (UNITY_2017 || UNITY_2018)
return string.Concat(Application.streamingAssetsPath, "/config/");
#else
switch (Application.platform)
{
case RuntimePlatform.WindowsEditor:
outPath = string.Concat("file: //",Application.streamingAssetsPath, "/config/");
return outPath;
case RuntimePlatform.IPhonePlayer:
outPath = string.Concat("file: //",Application.streamingAssetsPath, "/config/");
return outPath;
default:
outPath = string.Concat(Application.streamingAssetsPath, "/config/");
return outPath;
}
#endif