准备
- 编辑器中的文件夹属于DefaultAssets类型的资源
- EditorGUILayout.ObjectField 可以获取对象的引用
- AssetDatabase.GetAssetPath可通过对象的实例id获取资源路径
- DirectoryInfo 可获取目录内文件信息
- Path.GetFileNameWithoutExtension 可获取无后缀的文件名
示例1
弹出窗口 选择文件夹 打印文件夹内文件名文章来源:https://www.toymoban.com/news/detail-859856.html
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窗口打印文件名文章来源地址https://www.toymoban.com/news/detail-859856.html
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]);
}
}
}
}
}
到了这里,关于Unity 获取文件夹引用并读取文件夹路径的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!