[Unity editor extension practice], extended Hierarchy menu

The effect after extending Hierarchy:

When we debug the battle, we need to select the corresponding general in the Hierarchy interface, and then operate the shortcut keys to control the general. Because of multiple operations, I found it cumbersome, so I searched the Internet for a way to expand the Hierarchy menu.

code show as below:

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

    private static void OnHierarchyGUI(int instanceID, Rect selectionRect)
    {
        if (!Application.isPlaying)
            return;
        var data = Selection.activeGameObject;
        if (data == null)
        {
            return;
        }
        if (Event.current != null
        && selectionRect.Contains(Event.current.mousePosition)
        && Event.current.button == 1
        && Event.current.type <= EventType.MouseUp
        && CheckShow())
        {
            Vector2 mousePosition = Event.current.mousePosition;
            EditorUtility.DisplayPopupMenu(new Rect(mousePosition.x, mousePosition.y, 0, 0), "Tools/战斗脚本控制", null);
            Event.current.Use();
        }
    }

    [MenuItem("Tools/战斗脚本控制/控制该武将")]
    public static void SelectGameObject1()
    {
        if (Application.isPlaying)
        {
            var data = Selection.activeGameObject;
            if (data != null)
            {
                var roleControll = data.GetComponent<RoleController>();
                if (roleControll != null)
                {
                    roleControll.PlayerControl = !roleControll.PlayerControl;
                }
            }
        }
    }

    private static bool CheckShow()
    {
        var data = Selection.activeGameObject;
        if (data != null)
        {
            var roleControll = data.GetComponent<RoleController>();
            if (roleControll != null)
            {
                return true;
            }
        }
        return false;
    }

Note that you must add your own conditions, otherwise Unity's native menu will be overwritten.

reference:

Unity Editor Hierarchy Extended Chinese Tutorial - Detailed Explanation of Chinar Graphics - ChinarCSDN's Blog - CSDN Blog

Guess you like

Origin blog.csdn.net/qq_33461689/article/details/123351964