项目上有个需求,需要读取某些文件然后自动生成代码,生成的代码编译完成后自动执行对应的代码,Unity有提供一个对应的方案[InitializeOnLoadMethod],比较简单,直接上代码吧
[MenuItem("Test/ComplierTest")]
static void TTTT()
{
EditorPrefs.SetBool("ComplierRun", true);
CreateCodeText();
}
public static void CreateCodeText()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("using UnityEngine;");
sb.AppendLine("using UnityEditor;");
sb.AppendLine();
sb.AppendLine("public class AutoRun");
sb.AppendLine("{");
sb.AppendLine("\t[InitializeOnLoadMethod]");
sb.AppendLine("\tstatic void ComplierRun()");
sb.AppendLine("\t{");
sb.AppendLine("\t\tif (EditorPrefs.GetBool(\"ComplierRun\"))");
sb.AppendLine("\t\t{");
sb.AppendLine("\t\t\tEditorPrefs.SetBool(\"ComplierRun\",false);");
sb.AppendLine("\t\t\tDebug.Log(\"ComplierRun\");");
sb.AppendLine("\t\t}");
sb.AppendLine("\t}");
sb.AppendLine("}");
sb.AppendLine();
string code = sb.ToString();
string path = Application.dataPath + @"\Script\Editor\AutoRun.cs";
Debug.Log(path);
File.WriteAllText(path, code);
AssetDatabase.Refresh();
}
通过菜单执行后会生成如下代码
using UnityEngine;
using UnityEditor;
public class AutoRun
{
[InitializeOnLoadMethod]
static void ComplierRun()
{
if (EditorPrefs.GetBool("ComplierRun"))
{
EditorPrefs.SetBool("ComplierRun",false);
Debug.Log("ComplierRun");
}
}
}
这段代码在编译后会自动执行ComplierRun()函数。