【问题标题】:How can I add a option to a GameObject in the Hierarchy context menu?如何在 Hierarchy 上下文菜单中向 GameObject 添加选项?
【发布时间】:2019-02-13 06:34:36
【问题描述】:
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


    【解决方案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] 代替,您可以将其添加到 Inspector 中的组件中

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

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

    [ContextMenuItem("reset this", "ResetExample")]
    public int example;
    
    private void ResetExample ()
    {
        example = 0;
    }
    

    【讨论】:

      【解决方案2】:

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

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

      您需要创建一个简单的脚本组件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-27
        • 2015-02-17
        • 2011-06-21
        • 2016-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多