Created
April 8, 2016 14:27
-
-
Save tkyaji/1b12431e79f45bca164fd19288f2e889 to your computer and use it in GitHub Desktop.
[Unity] Generate constants class from Assets/Resouces Directory.
This file contains 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
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