编辑器中获取选中的文件夹、文件路径
C#
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
public class MyEditorScript
{
[MenuItem("Assets/PrintSelectedFolderPath")]
static void PrintSelectedFolderPath()
{
// 第一种方式
// 只能访问选中的文件 选中的文件夹则不会打印
// 获取选中的对象 仅仅对File有效
var obj = Selection.activeObject;
// 获取选中对象的路径
string path = AssetDatabase.GetAssetPath(obj);
Debug.Log("通过Selection.activeObject获取的路径: " + path);
// -----------------第二种方式-------------------------------
//支持多选
string[] guids = Selection.assetGUIDs;//获取当前选中的asset的GUID
for (int i = 0; i < guids.Length; i++)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);//通过GUID获取路径
Debug.Log("通过GUID获取的路径"+Application.dataPath + assetPath.Substring(6));
}
//第三种方式访问路径
Debug.Log("遍历Object来获取对应的路径" + Application.dataPath + GetCurrentAssetDirectory().Substring(6));
}
public static string GetCurrentAssetDirectory()
{
foreach (var obj in Selection.GetFiltered<Object>(SelectionMode.Assets))
{
var path = AssetDatabase.GetAssetPath(obj);
if(string.IsNullOrEmpty(path))
continue;
if (System.IO.Directory.Exists(path))
{
return path;
}else if (System.IO.File.Exists(path))
{
return System.IO.Path.GetDirectoryName(path);
}
}
return "";
}
}
使用案例:
访问某个具体的文件:

三种方式都可以访问出路径:

访问某个具体的文件夹:

则第一种方式Selection.activeObject便不可行[笔者在这里踩坑~]
同样的,如果访问的文件夹内容为空,则三种方式均可打印出路径:

