- Home /
How to get the current selected folder of "Project" Window
I have a function script that creates an asset registered with menu item "Assets/Create/MyAsset".
It creates my asset directly under the Assets folder. Then I used Selection.activeObject, as explained here : http://forum.unity3d.com/threads/81359-how-to-get-currently-selected-folder-for-putting-new-Asset-into.
It works if I used right click to show the creation popup menu but does not work if I click on the Create Button in the toolbar of the Project Window.
I tried to add a MenuCommand to my menu item function but the context object is null. Does anyone know how to get the current selected folder in the Project Window?
Answer by OperationDogBird · Dec 09, 2013 at 10:09 PM
I needed this today, did a quick google.. didnt find a suitable method. Heres what i came up with, works well.
Required Namespaces: UnityEngine, UnityEditor, System.IO
var path = "";
var obj = Selection.activeObject;
if (obj == null) path = "Assets";
else path = AssetDatabase.GetAssetPath(obj.GetInstanceID());
if (path.Length > 0)
{
if (Directory.Exists(path))
{
Debug.Log("Folder");
}
else
{
Debug.Log("File");
}
}
else
{
Debug.Log("Not in assets folder");
}
I converted it to CSharp and specifically made it a method to check if an asset is a folder....
private static bool IsAssetAFolder(Object obj){
string path = "";
if (obj == null){
return false;
}
path = AssetDatabase.GetAssetPath(obj.GetInstanceID());
if (path.Length > 0)
{
if (Directory.Exists(path))
{
return true;
}
else
{
return false;
}
}
return false;
}
Answer by kimsama · Mar 05, 2015 at 07:32 AM
Check this out: https://gist.github.com/kimsama/ff69cca140468f92d755
It shows not only to get a selected folder in Project view but also all files under the selected folder even with filtering by its file extension.
/// <summary>
/// Retrieves selected folder on Project view.
/// </summary>
/// <returns></returns>
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;
}
/// <summary>
/// Recursively gather all files under the given path including all its subfolders.
/// </summary>
static IEnumerable<string> GetFiles(string path)
{
Queue<string> queue = new Queue<string>();
queue.Enqueue(path);
while (queue.Count > 0)
{
path = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories(path))
{
queue.Enqueue(subDir);
}
}
catch (System.Exception ex)
{
Debug.LogError(ex.Message);
}
string[] files = null;
try
{
files = Directory.GetFiles(path);
}
catch (System.Exception ex)
{
Debug.LogError(ex.Message);
}
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
yield return files[i];
}
}
}
}
// You can either filter files to get only neccessary files by its file extension using LINQ.
// It excludes .meta files from all the gathers file list.
var assetFiles = GetFiles(GetSelectedPathOrFallback()).Where(s => s.Contains(".meta") == false);
foreach (string f in assetFiles)
{
Debug.Log("Files: " + f);
}
Answer by PlayCreatively · Nov 20, 2020 at 07:51 PM
Doesn't need to be more complicated than these lines
string folderPath = AssetDatabase.GetAssetPath(Selection.activeInstanceID);
if (folderPath.Contains("."))
folderPath = folderPath.Remove(folderPath.LastIndexOf('/'));
Debug.Log(folderPath);
Answer by Jashengmato · Sep 04, 2013 at 02:25 AM
Hi! Same problem and just figure it out!
[MenuItem("JashEditor/AssetBunldes")]
public static void CreateAssetBunldes ()
{
Object[] selectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
foreach(Object obj in selectedAsset)
{
Debug.Log("Asset name: "+obj.name+" Type: "+obj.GetType()) ;
}
}
Select a folder then click menu item, you will get something like this in console:
Asset name: KPacketType Type: UnityEditor.MonoScript
Asset name: KLCPacket Type: UnityEditor.MonoScript
Asset name: Messages Type: UnityEngine.Object
Now you see, the only Object typed object is the folder.
NOTE: This works works only if you put just files that unity can recognize. (PDF, jar, and other funky stuff will also be detected as UnityEngine.Object)
This may be a solution for some cases but does not resolve all of them (try to play with the selection and you 'll see problems). $$anonymous$$oreover, as you said, specific files and elements are Object too and you can not be sure. That's why I won't mark it as a solution. Thanks for the answer anyway.
If you use this code, I would suggest you not to use DeepAssets for the Selection$$anonymous$$ode. It will send you all the subfolders of the selected folder too so you can't select the right one from the list.
Yep, you are right about the DeepAssets part. I thought 'bout the question one more time, and maybe we could use .Net api to check if the object on the specified path is a folder or a file. (See System.IO) How's that sounds?
XD
actually, I found some cases with a selected (but not active) folder and the selection does not get it. Too much time for too few features, I ll use the right click popup menu ins$$anonymous$$d.
This is a really good solution, in my opinion. To add on to this, once you have the selected objects you can use:
Path.GetExtension( AssetDatabase.GetAssetPath( obj ) )
This will give you the extension of the file which could help narrow down the type of object you're looking for. This answer helped me a ton! Thanks!
Answer by frmada · Mar 20, 2020 at 12:51 PM
Here you have my implementation to get the full path of a folder right-clicked on Project View. I am not sure if this what you were asking for, but I hope it helps someone.
private static string GetClickedDirFullPath()
{
string clickedAssetGuid = Selection.assetGUIDs[0];
string clickedPath = AssetDatabase.GUIDToAssetPath(clickedAssetGuid);
string clickedPathFull = Path.Combine(Directory.GetCurrentDirectory(), clickedPath);
FileAttributes attr = File.GetAttributes(clickedPathFull);
return attr.HasFlag(FileAttributes.Directory) ? clickedPathFull : Path.GetDirectoryName(clickedPathFull);
}
Your answer
Follow this Question
Related Questions
Help me please 1 Answer
GUI & GUILayout methods no longer work in OnSceneGUI() 1 Answer
Set script global variable value priority over editor values 1 Answer
How to fix losing System.Data.dll in Project? 2 Answers
Unity Inspector Interface 5 Answers