Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Unity] Generate constants class from Assets/Resouces Directory.
using UnityEngine;
using UnityEditor;
using System.IO;
// Put this file to under the Assets/Editor
public class GenerateResourceNames : EditorWindow {
[MenuItem("Edit/Generate ResourceNames.cs")]
private static void GenerateFile() {
if (!Directory.Exists ("./Assets/Scripts")) {
Directory.CreateDirectory ("./Assets/Scripts");
}
if (File.Exists ("./Assets/Scripts/ResourceNames.cs")) {
File.Delete ("./Assets/Scripts/ResourceNames.cs");
}
if (Directory.Exists ("./Assets/Resources")) {
using (StreamWriter writer = File.CreateText ("./Assets/Scripts/ResourceNames.cs")) {
writeResourceDir (writer, "ResourceNames", "./Assets/Resources", 0);
}
}
Debug.Log ("Generate File : Scripts/ResourceNames.cs");
}
private static void writeResourceDir(StreamWriter writer, string dir, string path, int deep) {
writer.WriteLine (getIndentStr (deep) + "public static class " + dir + " {");
string[] subDirs = Directory.GetDirectories (path);
foreach (string subDir in subDirs) {
string dirName = Path.GetFileName (subDir);
if (dirName.StartsWith (".")) {
continue;
}
writeResourceDir (writer, dirName, subDir, deep + 1);
}
string[] files = Directory.GetFiles (path);
foreach (string file in files) {
if (Path.GetFileName (file).StartsWith (".") || file.EndsWith (".meta")) {
continue;
}
writeResourceFile (writer, file, deep + 1);
}
writer.WriteLine (getIndentStr (deep) + "}");
}
private static void writeResourceFile(StreamWriter writer, string file, int deep) {
string fileName = Path.GetFileNameWithoutExtension (file);
fileName = System.Text.RegularExpressions.Regex.Replace (fileName, "[^a-zA-Z0-9_]", "");
string resourcePath = file.Substring ("./Assets/Resources/".Length);
string resourceFile = Path.Combine (Path.GetDirectoryName (resourcePath), Path.GetFileNameWithoutExtension (resourcePath));
writer.WriteLine (getIndentStr (deep) + "public const string " + fileName + " = \"" + resourceFile + "\";");
}
private static string getIndentStr(int deep) {
return "".PadRight (deep * 4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment