Skip to content

Instantly share code, notes, and snippets.

@tkyaji
Created April 8, 2016 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkyaji/1b12431e79f45bca164fd19288f2e889 to your computer and use it in GitHub Desktop.
Save tkyaji/1b12431e79f45bca164fd19288f2e889 to your computer and use it in GitHub Desktop.
[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