如何在“层次结构”上下文菜单中向GameObject添加选项?

时间:2019-02-12 20:13:14

标签: c# unity3d

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上添加选项/属性。

这是我尝试过的:

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菜单。 但是我想在层次结构中的对象上单击鼠标右键时添加此内容。单个对象或选定对象。

尝试true,1和true,-10或true,10

2 个答案:

答案 0 :(得分:2)

在这里https://docs.unity3d.com/Manual/class-PresetManager.html

您可以使用此操作更改通用对象添加到对象的默认组件,或为新型资产或对象创建预设

您将需要创建仅是脚本的组件

答案 1 :(得分:1)

请参见this post,这取决于更多参数。它将使用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]可以将其添加到检查器中的组件中

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

您还可以使用[ContextMenuItem]

将方法直接添加到检查器中仅一个字段的上下文菜单中
[ContextMenuItem("reset this", "ResetExample")]
public int example;

private void ResetExample ()
{
    example = 0;
}