ContextMenuItem, ContextMenu, MenuItem区别与联系
ContextMenuItem
用于给成员变量增加右键菜单
加在成员变量上,在成员变量上右键弹出右键菜单,对应的菜单函数只能是成员函数,不能是static函数
public class TestContextMenu : MonoBehaviour { [ContextMenuItem("Reset Count", "CtxtMenuItem_ResetCount")] public int m_Count; #if UNITY_EDITOR private void CtxtMenuItem_ResetCount() { m_Count = 0; } #endif }
ContextMenu
用于扩展自定组件的Script右键菜单
只能加在成员函数上,加在static函数上没效果
using UnityEngine; public class TestContextMenu : MonoBehaviour { public int m_Count; #if UNITY_EDITOR [ContextMenu("Another Reset Count")] private void CtxtMenu_PrintCount() { Debug.Log($"m_Count: {m_Count}"); } #endif }
MenuItem
a) 用于扩展内置组件的Script右键菜单
using UnityEditor; using UnityEngine; public static class TestMenuItem { [MenuItem("CONTEXT/Transform/Copy Position")] static void MenuItem_CopyPosition() { if (null == Selection.activeTransform) return; Vector3 pos = Selection.activeTransform.position; Debug.Log($"拷贝的Position为: ({pos.x}, {pos.y}, {pos.z})"); } }
b) 用于扩展菜单栏菜单
using UnityEditor; using UnityEngine; public static class TestMenuItem { [MenuItem("MyTools/Print Hello")] static void MenuItem_PrintHello() { Debug.Log($"Hello"); } }
参考
ContextMenu和ContextMenuItem_三分明月墨的博客-CSDN博客
Unity ContextMenu 扩展组件的环境菜单(在 Inspector 视图组件名称上的右击下拉菜单) - kingBook - 博客园 (cnblogs.com)