Unity编辑器扩展

本文详细介绍了如何扩展Unity编辑器,包括使用MenuItem添加菜单项,AddComponentMenu在组件菜单中添加选项,ContextMenu创建上下文命令,以及ScriptableObject, EditorWindow, Editor和ScriptableWizard的使用。这些特性可以帮助开发者自定义工作流程,提高效率。" 121432837,7691771,Unity中Json的深入理解与LitJson解析,"['Unity开发', 'Json解析', '数据格式', '编程', ' LitJson库']
摘要由CSDN通过智能技术生成

unity是一个强大的编辑器。 我们可以通过一些代码扩展它,达到提高工作效率的目的。

在开始写代码之前, 我们需要先知道一些前置知识。

  1. 命名空间。Unity的运行时和编辑器类分别存储在不同的Assemblies里:UnityEngine 和 UnityEditor。编写编辑器之前,需要 using UnityEditor
  2. 当想在编辑器中执行脚本时, 可以使用 attribute:[ExecuteInEditMode]通知编辑器, 被描述类的 OnGUI 和 Update 等函数在编辑模式也会被调用。
  3. 当代码在运行时和编辑器都需要执行时,可以使用 #if UNITY_EDITOR … #endif 宏来对编辑器代码做特殊处理。

本文主要介绍了以下几个方法:
- MenuItem
- AddComponentMenu
- ContextMenu
- ScriptableObject
- EditorWindow
- Editor
- ScriptableWizard

其中 MenuItem, AddComponentMenu, ContextMenu 并不会用到 UnityEditor 命名空间。

ScriptableObject, EditorWindow, Editor, ScriptableWizard 需要使用 UnityEditor 命名空间。


[MenuItem(“dir/name”)]:MenuItem属性允许您将菜单项添加到主菜单和 inspector context 菜单。

https://docs.unity3d.com/ScriptReference/MenuItem.html

  1. MenuItem必须定义子菜单, 如[MenuItem(“dir”)] 是不行的。
  2. MenuItem 属性必须写在一个静态方法之前;
using UnityEditor;
using UnityEngine;
public class t_MenuItem : MonoBehaviour {
    [MenuItem("MyMenu/Do Something")]
    static void DoSomething() {
        Debug.Log("Doing Something...");
    }

    [MenuItem("MyMenu/Log Selected Transform Name")]
    static void LogSelectedTransformName() {
        Debug.Log("Selected Transform is on " + Selection.activeTransform.gameObject.name + ".");
    }

    [MenuItem("MyMenu/Log Selected Transform Name", true)]
    static bool ValidateLogSelectedTransformName() {
        return Selection.activeTransform != null;
    }

    [MenuItem("MyMenu/Do Something with a Shortcut Key %g")]
    static void DoSomethingWithAShortcutKey() {
        Debug.Log("Doing something with a Shortcut Key...");
    }

}

效果todo1

效果todo2

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值