Skip to content

Instantly share code, notes, and snippets.

@allanolivei
Created February 27, 2014 21:38
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save allanolivei/9260107 to your computer and use it in GitHub Desktop.
Save allanolivei/9260107 to your computer and use it in GitHub Desktop.
Unity 3d : Get Selected Folder in Project Window
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
public static class UnityUtil
{
public static string GetSelectedPathOrFallback()
{
string path = "Assets";
foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
{
path = AssetDatabase.GetAssetPath(obj);
if ( !string.IsNullOrEmpty(path) && File.Exists(path) )
{
path = Path.GetDirectoryName(path);
break;
}
}
return path;
}
}
@pointcache
Copy link

Thank you!

@raystudio9236
Copy link

Thanks. It's very helpful to me! :)

@SilentSin
Copy link

That will only work if a file is selected. Here's an alternative that supports folders too:

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 "Assets";
}

@nntgam
Copy link

nntgam commented Aug 9, 2020

and any way to open this folder like EditorGUIUtility.PingObject?? I want fast jump to this folder on editor (because I'm searching file and want jump to this folder)

@wappenull
Copy link

@AlexZonov
Copy link

Stable cross-platform solution, supports folders and files. Default path is Application.dataPath

public static string GetProjectWindowFolder()
{
	string projectPath = new DirectoryInfo(Application.dataPath).Parent.FullName;
	string objectProjectPath = AssetDatabase.GetAssetPath(Selection.activeObject);
	string objectAbsolutePath = string.IsNullOrEmpty(objectProjectPath) ? Application.dataPath : $"{projectPath}/{objectProjectPath}";
	string objectCorrectAbsolutePath = objectAbsolutePath.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar);
	string folderAbsolutePath = File.Exists(objectCorrectAbsolutePath) ? Path.GetDirectoryName(objectCorrectAbsolutePath) : objectCorrectAbsolutePath;
	return Path.GetRelativePath(projectPath, folderAbsolutePath);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment