平时在工作中有时可能会碰到想要获得自己项目文件夹下文件名中包含某个特定字符或字符串的文件及其路径,这时如果只是在Unity的Project栏中输入这个特定的字符串来查找的话,虽然可以找到这些文件,但要获取路径就只能手动打开每个文件所在的文件夹位置。作为一个程序员,这样做显然效率太低,不符合程序员的Geek风格,所以我想到利用Unity的Editor功能写一个小脚本来获取需要的文件路径,代码如下。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
public class GetDir : MonoBehaviour {
//菜单栏创建自定义工具
[MenuItem("Tools/GetFileDirctory")]
static void CheckProject()
{
List
dirs = new List
();
GetDirs(Application.dataPath, ref dirs);
}
//第一个参数是想要查询的文件夹路径,第二个参数是用来存放查询所获得的文件路径
private static void GetDirs(string path,ref List
dirs)
{
foreach(string dirpath in Directory.GetFiles(path))
{
//获取文件名中包含“_vcc”的文件路径
if (System.IO.Path.GetFileNameWithoutExtension(dirpath).Contains("_vcc"))
{
//查询获得的文件路径字符串以“Assets”开头
dirs.Add(dirpath.Substring(dirpath.IndexOf("Assets")));
Debug.Log(dirpath.Substring(dirpath.IndexOf("Assets")));
}
}
//递归调用自身来遍历所有子文件夹
if (Directory.GetDirectories(path).Length > 0)
{
foreach(string subDir in Directory.GetDirectories(path))
{
GetDirs(subDir, ref dirs);
}
}
}
}