Create a Custom Menu Item in Unity Editor
You often notice that many of the Unity assets add a new menu item after importing it to the Unity project. Those menu items are created by the author of the assets.
Creating a menu item may be useful for you and your team. instead of doing the same task again and again, you can create a menu and use it with just within click. So, in this tutorial, I am going to show you how to create a custom menu item in your Unity project with the help of C# programming.
In order to add your own custom menu in the Unity editor via C# programming, you must have to use the following namespaces:
using UnityEditor; using UnityEngine;
Note that, it is not necessary to attach the script to any of the GameObject.
Now let’s continue learning…
Creating a top-level menu item
Below is a simple C# program for Unity to create a top-level menu item with the menu name “CodeSpeedy Menu”:
using UnityEditor; using UnityEngine; public class MyNewMenu : MonoBehaviour { // Add a Top Level menu item with the name "CodeSpeedy Menu" and create a submenu with the name "Submenu Item" under it. [MenuItem("CodeSpeedy Menu/Submenu Item")] private static void MyMenuInAction() { // Run the code after clicking the menu item Debug.Log("Submenu from my Custom Menu Item clicked"); } }
In the above program, the code inside MyMenuInAction()
run when the submenu clicked. If you want multiple submenu, then below is the code for it:
using UnityEditor; using UnityEngine; public class MyNewMenu : MonoBehaviour { // Add a Top Level menu item with the name "CodeSpeedy Menu" and create a submenu with the name "Submenu Item" under it. [MenuItem("CodeSpeedy Menu/Submenu Item")] private static void MyMenuInAction() { // Run the code after clicking the menu item Debug.Log("Submenu from my Custom Menu Item clicked"); } // Another submenu in the same "CodeSpeedy Menu" [MenuItem("CodeSpeedy Menu/Another Submenu Item")] private static void AnotherMyMenuInAction() { // Run the code after clicking the menu item Debug.Log("Another Submenu from my Custom Menu Item clicked"); } }
Creating a submenu under the built-in Unity top-level menu
If you want to create a submenu under any of the existing built-in Unity menu, then the process is the same. You just have to mention the menu name. See the example below where I am creating a submenu under the Window menu:
using UnityEditor; using UnityEngine; public class MyNewMenu : MonoBehaviour { // Add a submenu "My Submenu" under "Window" menu [MenuItem("Window/My Submenu")] private static void MySubmenuInAction() { // Run the code after clicking the submenu item Debug.Log("My Submenu Item clicked"); } }
Leave a Reply