MenuItem
- Game Development course
- Expert
- Lesson 33/47
- 4 min
Learn to add a menu entry with MenuItem.
Adding to the Top Menu with the MenuItem Attribute
To add custom tools or functions to Unity's top menu bar, the [MenuItem("Menu/Path")] attribute is used. This attribute is placed above a static method and invokes it when clicked.
[MenuItem("Tools/Clear Enemies")]
static void ClearEnemies()
{
Debug.Log("Enemies cleared");
}Defining Keyboard Shortcuts
Keyboard shortcuts can be configured by appending special modifier symbols to the MenuItem path. For example, % represents Ctrl/Cmd, # represents Shift, and & represents Alt. This accelerates recurring actions with a single keystroke combination.
// %g -> represents Ctrl+G or Cmd+G shortcut
[MenuItem("Tools/Quick Create %g")]
static void QuickCreate() {}Practice Menu Command Simulation
Simulate menu path: execute Debug.Log("Menu calisti: " + menuYolu);.
Starter code
using System;
public static class Debug
{
public static void Log(object message) => Console.WriteLine(message);
}
public class Program
{
public static void Main()
{
string menuYolu = "Araclar/Temizle";
// menuYolu ile konsola mesaj yazdir
}
}Sample solution
using System;
public static class Debug
{
public static void Log(object message) => Console.WriteLine(message);
}
public class Program
{
public static void Main()
{
string menuYolu = "Araclar/Temizle";
Debug.Log("Menu calisti: " + menuYolu);
}
}Expected output
Menu calisti: Araclar/Temizle
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword is mandatory for a method decorated with the MenuItem attribute?
- override
- static Correct answer
- abstract
- virtual
Explanation: The method must be static so the Unity editor can invoke the menu command without requiring an object instance.
2 MenuItem Attribute Definition
[____("Araclar/Rapor")]
[MenuItem("Araclar/Rapor")]
Explanation: The MenuItem attribute is used to bind the method to the top menu bar.
3 Menu and Shortcut Symbols
| Term | Meaning |
|---|---|
MenuItem |
Attribute adding commands to top menu |
static |
Modifier required for MenuItem methods |
% (Kısayol) |
Ctrl or Cmd key in shortcut definitions |
# (Kısayol) |
Shift key in shortcut definitions |