簡體   English   中英

如何在Hierarchy上下文菜單中為GameObject添加選項?

[英]How can I add a option to a GameObject in the Hierarchy context menu?

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下面的編輯器菜單中創建Test選項。 但我想在層次結構中的單個或多個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")]

它將在編輯器頂部和Export中添加一個新的GameObject菜單。 但是我想在對象層次結構中的對象上單擊鼠標右鍵時添加此項。 單個對象或所選對象。

試過真,1和真,-10或真,10

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

您可以使用它來更改添加到通用對象的對象的默認組件,或者為新類型的資產或對象創建預設

您將需要創建一個簡單的腳本組件

這篇文章取決於更多參數。 它將使用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM