首页 > 解决方案 > 如何在 Hierarchy 上下文菜单中向 GameObject 添加选项?

问题描述

using UnityEditor;
using UnityEngine;

public class Test : EditorWindow
{
    [MenuItem("GameObject/Test")]
    static void Tests()
    {
        int width = 340;
        int height = 300;

        int x = (Screen.currentResolution.width - width) / 2;
        int y = (Screen.currentResolution.height - height) / 2;

        GetWindow<Test>().position = new Rect(x, y, width, height);
    }
}

这将在 GameObject 下方顶部的编辑器菜单中创建测试选项。但我想在层次结构中的单个或多个 GameObject/s 上添加选项/属性,而不是编辑器顶部菜单。

这是我尝试过的:

using UnityEditor;
using UnityEngine;

public class ExportObjects : EditorWindow
{
    [MenuItem("GaemObject/Export", true, 1)]
    static void Export()
    {
        int width = 340;
        int height = 300;

        int x = (Screen.currentResolution.width - width) / 2;
        int y = (Screen.currentResolution.height - height) / 2;

        GetWindow<ExportObjects>().position = new Rect(x, y, width, height);
    }
}

但它什么也没做,它没有向层次结构中对象的右键单击鼠标上下文菜单添加任何内容。

如果我换行:

[MenuItem("GaemObject/Export", true, 1)]

到:

[MenuItem("GaemObject/Export")]

它将在编辑器和导出的顶部添加一个新的 GameObject 菜单。但是我想在层次结构中的对象上单击鼠标右键时添加它。单个对象或选定对象。

试过真,1 和真,-10 或真,10

标签: c#unity3d

解决方案


请参阅这篇文章,它取决于更多参数。它将使用priority参数出现在层次结构上下文菜单中,例如-10

[MenuItem("GameObject/Test", false, -10)]

没有选项可以控制应显示或不显示哪些对象。

但是您可以通过添加验证方法来启用和禁用按钮。例如,仅当所选对象具有Camera组件时才启用该方法

// true turns it into a validation method
[MenuItem("GameObject/Test", true, -10)]
private static bool IsCanera()
{
    return Selection.activeGameObject != null && Selection.activeGameObject.GetComponent<Camera>();
}

以相同的方式,但[ContextMenu]您可以将其添加到 Inspector 中的组件中

[ContextMenu("Example")]
private void DoSomething()
{
    // Do something
}

您还可以使用以下方法将方法直接添加到检查器中仅一个字段的上下文菜单中[ContextMenuItem]

[ContextMenuItem("reset this", "ResetExample")]
public int example;

private void ResetExample ()
{
    example = 0;
}

推荐阅读