Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Jumblegreen · Apr 03, 2012 at 06:44 PM · editorfolder

How do I enumerate the contents of an asset folder?

I am writing an editor script to create a text asset containing optimised level information based on a combination of game objects in the editor and assets in an asset folder.

I can get at the game-objects in the editor easily enough but I can't find a way to enumerate my way though all the assets in the currently selected asset folder.

I can get the currently selected 'Object' easily enough using 'Object objSelected = Selection.activeObject;' but I am stuck as to how I can a) cast that to folder or get some kind of folder interface from it b) get the list of assets inside the folder c) determine the type of those assets and cast them to useful types (game-objects text assets etc...)

All help appreciated.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Jan 25, 2016 at 03:56 PM -1
Share

related .. http://answers.unity3d.com/questions/1133078/recover-path-information-for-an-asset-but-at-runti.html

2 Replies

· Add your reply
  • Sort: 
avatar image
10
Best Answer

Answer by Jumblegreen · Apr 04, 2012 at 11:46 AM

Thanks for this. It was the lead I needed. What I wanted to do was get access to all the assets in the currently selected asset folder. This is the code I ended up with.

I hope somebody else finds this useful.

             if (Selection.activeObject != null ){
             
             Object objSelected = Selection.activeObject;
             
             string sAssetFolderPath = AssetDatabase.GetAssetPath(objSelected);

                             // Construct the system path of the asset folder 
             string sDataPath  = Application.dataPath;
             string sFolderPath = sDataPath.Substring(0 ,sDataPath.Length-6)+sAssetFolderPath;            

                             // get the system file paths of all the files in the asset folder
             string[] aFilePaths = Directory.GetFiles(sFolderPath);

                             // enumerate through the list of files loading the assets they represent and getting their type
 
             foreach (string sFilePath in aFilePaths) {
                 string sAssetPath = sFilePath.Substring(sDataPath.Length-6);
                 Debug.Log(sAssetPath);
                 
                 Object objAsset =  AssetDatabase.LoadAssetAtPath(sAssetPath,typeof(Object));
                 
                 Debug.Log(objAsset.GetType().Name);
             }

         }

Its worth noting that the 'AssetDatabase.LoadAllAssetsAtPath ' call loads all the assets in a single FILE. It DOES NOT load all the assets in a directory which is why you have to get your own list of folder contents.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image kaocat · Sep 22, 2014 at 04:11 AM 0
Share

amazing!! thx for this code !!! i can get folder's obj let project can ez be fixs ! real thx!

avatar image a trained monkey · Jun 22, 2015 at 04:51 PM 0
Share

The example above will only grab files in the immediate directory, if you want to search sub-directories too, add the SearchOption SearchOption.AllDirectories

 Directory.GetFiles( folderPath,searchPattern:"*", searchOption: SearchOption.AllDirectories );


avatar image jonc113 · Jul 26, 2015 at 03:12 AM 1
Share

For me, Directory.GetFiles() also finds the .meta files, easily solved by adding this line right after the foreach:

 if (sFilePath.EndsWith(".meta")) continue ;
avatar image gabe2o2 · Mar 20, 2020 at 08:10 PM 0
Share

8 years later and this still helped me out. BIG thanks for that "Directory.GetFiles" method. Literally was the piece I was missing to get things working as I wanted, and no one else even mentioned it in their posts

avatar image
3

Answer by kimsama · Mar 05, 2015 at 07:27 AM

You can gather all files under the selected folder in the Project view as the following:

     // 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);
     }

     /// <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];
                 }
             }
         }
     }
     
 

Check at the following gist: https://gist.github.com/kimsama/ff69cca140468f92d755

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Change Default Script Folder 5 Answers

Unity Script Editor Not Working 1 Answer

Script Editors for Unity 3 Answers

The Script Equivilent of dragging a hierarchy of meshes over a preexisting prefab? 0 Answers

Tracking down causes of Editor errors. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges