-小狗饼干- / 洛12
399 字
2 分钟
Unity 编辑器扩展(3):组件菜单栏扩展
组件新建菜单扩展
默认情况下,我们自己编写的脚本会被放置在 “Component > Scripts” 中。使用 AddComponentMenu 特性标记脚本可以指定脚本在 Component 菜单中的路径。
using System.Collections;using System.Collections.Generic;using UnityEngine;
[AddComponentMenu("Test/TestAddComponentMenu")]public class TestAddComponentMenu : MonoBehaviour{ // Start is called before the first frame update void Start() {
}
// Update is called once per frame void Update() {
}}[!Note]
根据官方 API 文档的说法,需要重新启动才可以生效,但是在实际使用中修改完成就可生效。
该特性也提供另一个重载 AddComponentMenu(string menuName, int order) 用以对同一路径下的同级脚本进行排序,order 的值越大排序越靠下。
组件菜单扩展
ContextMenu 特性
该特性用于自定义扩展脚本在 Inspector 窗口中的右键菜单,通常用于快捷的设置数据。该特性需要标记脚本内的非静态方法。
using System.Collections;using System.Collections.Generic;using UnityEngine;
public class TestMonoBehaviour : MonoBehaviour{ public int Num = 0;
[ContextMenu("Reset Num")] private void ResetNum() { Num = 1; }}该特性接受三个参数 ContextMenu(string itemName, bool isValidateFunction, int priority),可参照《Unity 编辑器扩展(2):菜单栏扩展》。
ContextMenuItem 特性
该特性可将自定义方法添加到字段的右键菜单中。
using System.Collections;using System.Collections.Generic;using UnityEngine;
public class TestMonoBehaviour : MonoBehaviour{ [ContextMenuItem("Reset Num", "ResetNum")] public int Num = 0;
private void ResetNum() { Num = 1; }}该特性有两个参数,一个变量:
| 参数名 | 类型 | 描述 |
|---|---|---|
| name | string | 在右键菜单中的名称 |
| function | string | 要执行的方法 |
| order | int | 在右键菜单中的排序(可选) |
使用示例:
[ContextMenuItem(string name, string function, order = int)] Unity 编辑器扩展(3):组件菜单栏扩展
https://blog.unknowncat2048.top/posts/unity-editor-extension-3/