Last active
August 22, 2024 06:28
-
-
Save kimsama/ff69cca140468f92d755 to your computer and use it in GitHub Desktop.
Code snip which shows gather all files under selected folder in Unity's Project View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment