Skip to content

Instantly share code, notes, and snippets.

@marcosecchi
Last active January 30, 2024 10:24
Show Gist options
  • Save marcosecchi/2f0ac47c7da112b35d3d9f55a4492173 to your computer and use it in GitHub Desktop.
Save marcosecchi/2f0ac47c7da112b35d3d9f55a4492173 to your computer and use it in GitHub Desktop.
Generating menu items at runtime in Unity
using UnityEngine;
using UnityEditor;
using System.Text;
namespace TheBitCave {
public class MenuItemGenerator {
/// <summary>
/// Generates a list of menuitems from an array
/// </summary>
[MenuItem("Assets/TheBitCave/Generate Menu Items")]
static void GenerateMenuItems() {
// the generated filepath
string scriptFile = Application.dataPath + "/GeneratedMenuItems.cs";
// an example string array used to generate the items
string[] ar = new string[] {"item 1", "item 2", "item 3", "item 4"};
// The class string
StringBuilder sb = new StringBuilder();
sb.AppendLine("// This class is Auto-Generated");
sb.AppendLine("using UnityEngine;");
sb.AppendLine("using UnityEditor;");
sb.AppendLine("");
sb.AppendLine(" public static class GeneratedMenuItems {");
sb.AppendLine("");
// loops though the array and generates the menu items
for(int i = 0; i < ar.Length; i++) {
sb.AppendLine(" [MenuItem(\"Assets/The Bit Cave/Generated/" + ar[i] + "\")]");
sb.AppendLine(" private static void MenuItem" + i.ToString() + "() {");
sb.AppendLine(" Debug.Log(\"Selected item: " + ar[i] + "\");");
sb.AppendLine(" }");
sb.AppendLine("");
}
sb.AppendLine("");
sb.AppendLine("}");
// writes the class and imports it so it is visible in the Project window
System.IO.File.Delete(scriptFile);
System.IO.File.WriteAllText(scriptFile, sb.ToString(), System.Text.Encoding.UTF8);
AssetDatabase.ImportAsset("Assets/GeneratedMenuItems.cs");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment