当前位置:   article > 正文

Unity扩展编辑器功能的特性

Unity扩展编辑器功能的特性

1.添加分组标题

用于在Unity的Inspector视图中为属性或变量组创建一个自定义的标题或头部,有助于在Inspector中组织和分类不同的属性,使其更易于阅读和管理。

  1. [Header("Common Properties")]
  2. public float MouseSensitivity = 5;
  3. public float SmothTime = 0.1f;
  4. void Start()
  5. {
  6. //Header应用于属性和字段上
  7. }

2.Assets创建功能添加菜单

用于在Unity的Project视图的右键菜单中创建一个新的自定义资源(Asset)。这个属性通常用于脚本,这些脚本定义了可以在Unity项目中被实例化为Asset的自定义数据类型。

  1. [CreateAssetMenu(menuName ="MyCustomMenu/CustomData")]
  2. public class MyCustomData : ScriptableObject
  3. {
  4. //CreateAssetMenu主要应用于类上
  5. }

3.工具栏添加菜单

用于在Unity编辑器的菜单栏中创建自定义菜单项。这个属性是UnityEditor命名空间中的一部分,并且它要求与之关联的方法必须是静态的

  1. [MenuItem("CustomMenu/CustomFunc")]
  2. public static void MenuCommand()
  3. {
  4. //MenuItem应用于静态方法(static)上
  5. }

4.添加组件菜单

用于自定义Unity编辑器中“Component”菜单下的显示选项,当你尝试向场景中的GameObject添加组件时。这个特性通常与继承自 MonoBehaviour的类一起使用,以便在Inspector窗口中提供自定义的添加方式。

  1. [AddComponentMenu("MyCustomMenu/CustomComponent")]
  2. public class MyCustomData : MonoBehaviour
  3. {
  4. //与继承自MonoBehaviour的类一起使用
  5. }

5.添加字段右键菜单

用于在对象的上下文菜单中添加一个自定义菜单项。当用户在Unity编辑器中选择一个具有这个特性附加的组件或资源,并右键点击时,该菜单项就会出现。

  1. [ContextMenuItem("CustomOption", "FuncA")]
  2. public int customValue;
  3. public void FuncA()
  4. {
  5. //第一个参数为选项名称,第二个参数为被调用的函数的名称
  6. }

6. 组件自定义编辑器

用于指定一个自定义的编辑器类来编辑某个特定的Unity组件(通常是继承自MonoBehaviour的类)

  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEditor;
  4. // 这是你要为其创建自定义编辑器的组件
  5. [AddComponentMenu("MyComponent")]
  6. public class MyComponent : MonoBehaviour
  7. {
  8. public int someValue = 0;
  9. public bool isBool;
  10. // ... 其他组件字段 ...
  11. }
  12. // 自定义编辑器类,用于编辑MyComponent
  13. [CustomEditor(typeof(MyComponent))]
  14. public class MyComponentEditor : Editor
  15. {
  16. // 获取当前被编辑的MyComponent实例
  17. private MyComponent myTarget;
  18. // 当编辑器被创建时调用
  19. void OnEnable()
  20. {
  21. // 获取当前编辑的对象
  22. myTarget = (MyComponent)target;
  23. }
  24. // 在Inspector窗口中绘制自定义UI
  25. public override void OnInspectorGUI()
  26. {
  27. // 绘制默认的组件字段
  28. DrawDefaultInspector();
  29. // 添加自定义的编辑器GUI
  30. GUILayout.Space(10); // 添加一些间距
  31. EditorGUILayout.LabelField("自定义编辑器扩展", EditorStyles.boldLabel);
  32. // 添加一个字段的自定义编辑器
  33. myTarget.someValue = EditorGUILayout.IntField("自定义值", myTarget.someValue);
  34. // 确保更改被应用
  35. if (GUI.changed)
  36. {
  37. EditorUtility.SetDirty(myTarget); // 标记目标为已更改
  38. }
  39. }
  40. }

7.编辑器模式下执行脚本的 MonoBehaviour

        通常情况下,MonoBehaviour 中的代码只在游戏运行时(即按下播放按钮后)才会被执行。但是,为脚本添加[ExecuteInEditMode]特性后在 Unity 编辑器的非运行状态下也能执行某些逻辑

        使用[ExecuteInEditMode]特性后,Unity 会在编辑器中自动调用该 MonoBehaviour 的 Update()OnValidate() 和其他在运行时调用的函数(除了 Awak()、Start()外,因为 Awak()、Start() 只在游戏运行时被调用一次)。这对于开发需要在编辑器中即时反馈的自定义编辑器工具或脚本非常有用,比如自定义的着色器编辑器、地形编辑器、或是需要在编辑器中预览效果的脚本。

[ExecuteInEditMode]

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号