准备
- 编辑器中的文件夹属于DefaultAssets类型的资源
- EditorGUILayout.ObjectField 可以获取对象的引用
- AssetDatabase.GetAssetPath可通过对象的实例id获取资源路径
- DirectoryInfo 可获取目录内文件信息
- Path.GetFileNameWithoutExtension 可获取无后缀的文件名
示例1
弹出窗口 选择文件夹 打印文件夹内文件名
using UnityEditor;
using System.IO;
using System.Linq;
public class FolderInFileName
{DefaultAsset folder;string folderPath;string[] result;int length;public void OnGUI(){folder = EditorGUILayout.ObjectField("选择文件夹", folder, typeof(DefaultAsset), false) as DefaultAsset;if (folder != null){folderPath = AssetDatabase.GetAssetPath(folder.GetInstanceID());DirectoryInfo info = new DirectoryInfo(folderPath);var files = info.GetFiles("*", SearchOption.AllDirectories).Where(value => { return !value.FullName.EndsWith(".meta"); }).ToArray();if (files != null){length = files.Length;result = new string[length];for (int i = 0; i < length; i++)result[i] = Path.GetFileNameWithoutExtension(files[i].Name);EditorGUILayout.Space();EditorGUILayout.LabelField("文件夹路径", folderPath);EditorGUILayout.LabelField("文件数量", length.ToString());for (int i = 0; i < length; i++)EditorGUILayout.LabelField($"文件 {i + 1}", result[i]);}}else EditorGUILayout.HelpBox("没有设置文件夹或文件后缀", MessageType.Warning); }
}public class PrintFolderInFileName : EditorWindow
{FolderInFileName folderInFileNames = new FolderInFileName();[MenuItem("Customs/PrinFileNams")]private static void OpenWindow(){var window = GetWindow<PrintFolderInFileName>();window.Show();}private void OnGUI(){folderInFileNames.OnGUI();}
}
示例2
点击文件夹 Inspector窗口打印文件名
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;[CustomEditor(typeof(DefaultAsset))]
public class ShowFolderInFile : Editor
{public override void OnInspectorGUI(){string path = AssetDatabase.GetAssetPath(target);GUI.enabled = true;if (Directory.Exists(path)){if (path != null){DirectoryInfo info = new DirectoryInfo(path);var files = info.GetFiles("*", SearchOption.AllDirectories).Where(value =>{ return !value.FullName.EndsWith(".meta"); }).ToArray();if (files != null){var length = files.Length;var result = new string[length];for (int i = 0; i < length; i++)result[i] = Path.GetFileNameWithoutExtension(files[i].Name);EditorGUILayout.Space();EditorGUILayout.LabelField("文件夹路径", path);for (int i = 0; i < length; i++)EditorGUILayout.LabelField($"文件 {i + 1}", result[i]);}}}}
}