kingBook

导航

Unity Editor Hierarchy下拉菜单扩展

TestHierarchyPopupMenuEditor.cs

using UnityEditor;
using UnityEngine;

public class TestHierarchyPopupMenuEditor : ScriptableObject {

    [MenuItem("GameObject/Create New Child", true)]
    private static bool ValidateCreateChild() {
        GameObject[] gameObjects = Selection.gameObjects;
        return gameObjects.Length > 0;
    }

    [MenuItem("GameObject/Create New Child", false, 11)]
    private static void CreateChild() {
        GameObject[] gameObjects = Selection.gameObjects;
        for (int i = 0; i < gameObjects.Length; i++) {
            var child = new GameObject("New Child");
            child.transform.parent = gameObjects[i].transform;
        }
    }
}

修改为按下并释放鼠标中键弹出指定菜单
TestHierarchyPopupMenuEditor.cs

using UnityEditor;
using UnityEngine;

public class TestHierarchyPopupMenuEditor : ScriptableObject {

    [InitializeOnLoadMethod]
    private static void StartInitializeOnLoadMethod() {
        EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI;
    }

    private static void OnHierarchyGUI(int instanceID, Rect selectionRect) {
        if (Event.current!=null) {
            Debug.Log($"button:{Event.current.button}, type:{Event.current.type}");
        }
        
        if (Event.current != null && Event.current.button == 2 && Event.current.type == EventType.MouseUp) { // 按下并释放鼠标中键时
            //if (Selection.activeTransform) { // 选中激活一个 Transform 时才弹出
                Vector2 mousePosition = Event.current.mousePosition;
                EditorUtility.DisplayPopupMenu(new Rect(mousePosition.x, mousePosition.y, 0, 0), "GameObject/", null); // 弹出 GameObject 菜单
            //}
        }
    }
}
  • 在 Hierarchy 中选择多个对象时,扩展右键菜单会出现执行多次的情况,在某些时候不需要这样的操作,可以参考如下示例只执行一次。
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;

public class EditorTestDuplicateObjects : ScriptableObject  {

    private static bool s_isExecute;

    [MenuItem("GameObject/Duplicate Objects", true)]
    private static bool ValidateDuplicateObjects() {
        GameObject[] gameObjects = Selection.gameObjects;
        return gameObjects.Length > 0;
    }

    [MenuItem("GameObject/DuplicateObjects", false, 11)]
    private static void DuplicateObjects() {
        if (s_isExecute) {
            s_isExecute = false;
			Debug.Log("执行复制对象操作");
        }
    }

    [InitializeOnLoadMethod]
    private static void StartInitializeOnLoadMethod() {
        EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI;
    }

    private static void OnHierarchyGUI(int instanceID, Rect selectionRect) {
        if (Event.current != null && Event.current.button == 1 && Event.current.type == EventType.MouseUp) {
            s_isExecute = true;
        }
    }
}
#endif

posted on 2022-04-20 17:45  kingBook  阅读(414)  评论(0编辑  收藏  举报