Unity判断某个路径或文件是否存在
发表于2018-10-09
1、判断文件或文件夹的存在与否
引用 System.IO 命名空间
string dirPath = "..."; DirectoryInfo mydir = new DirectoryInfo(dirPath); if(mydir.Exists) { }
string path = "..."; if(!System.IO.Exists(path)){ System.IO.CreateDirectory(path); print ("文件夹不存在,创建"); }
2、判断某个路径是否存在
在Unity3D开发项目时,有时需要进行路径是否存在的断定:
System.IO.File.Exist(string filePath); System.IO.Directory(string dirPath);
注意这接口只是判定磁盘(闪存)物理路径上是否存在某个文件(目录),我们知道Application.streamingAssetsPath取到的是StreamingAssets资源包路径,此资源包是Unity3D在编译时将工程目录StreamingAssets中的资源编译打包后生成的。
所以,我们尝试:
System.IO.File.Exist(Application.StreamingAssets + "/file.txt");
这样去判定文件是否存在时,会返回False,因为这本就不是一个文件物理路径。
Application.persistentDataPath所指向路径,及其下的文件不会被Unity3D编译打包,其中的文件或目录是可以使用System.IO.File.Exist()接口判断是否存在的
如果文件在Application.StreamingAssets中,用System.IO.File.Exist是取不到他的存在与否的,而persistentDataPath就可以. persistentDataPath是真实存在的物理路径,如果做热更新资源也是放到persistentDataPath目录
通过上述介绍, 相信大家都能掌握如何去判断某个路径或文件是否存在。