赞
踩
用于在Unity的Inspector视图中为属性或变量组创建一个自定义的标题或头部,有助于在Inspector中组织和分类不同的属性,使其更易于阅读和管理。
- [Header("Common Properties")]
- public float MouseSensitivity = 5;
- public float SmothTime = 0.1f;
-
- void Start()
- {
- //Header应用于属性和字段上
- }
用于在Unity的Project视图的右键菜单中创建一个新的自定义资源(Asset)。这个属性通常用于脚本,这些脚本定义了可以在Unity项目中被实例化为Asset的自定义数据类型。
- [CreateAssetMenu(menuName ="MyCustomMenu/CustomData")]
- public class MyCustomData : ScriptableObject
- {
- //CreateAssetMenu主要应用于类上
- }
用于在Unity编辑器的菜单栏中创建自定义菜单项。这个属性是UnityEditor
命名空间中的一部分,并且它要求与之关联的方法必须是静态的。
- [MenuItem("CustomMenu/CustomFunc")]
- public static void MenuCommand()
- {
- //MenuItem应用于静态方法(static)上
- }
用于自定义Unity编辑器中“Component”菜单下的显示选项,当你尝试向场景中的GameObject添加组件时。这个特性通常与继承自 MonoBehaviour
的类一起使用,以便在Inspector窗口中提供自定义的添加方式。
- [AddComponentMenu("MyCustomMenu/CustomComponent")]
- public class MyCustomData : MonoBehaviour
- {
- //与继承自MonoBehaviour的类一起使用
- }
用于在对象的上下文菜单中添加一个自定义菜单项。当用户在Unity编辑器中选择一个具有这个特性附加的组件或资源,并右键点击时,该菜单项就会出现。
- [ContextMenuItem("CustomOption", "FuncA")]
- public int customValue;
-
- public void FuncA()
- {
- //第一个参数为选项名称,第二个参数为被调用的函数的名称
- }
用于指定一个自定义的编辑器类来编辑某个特定的Unity组件(通常是继承自MonoBehaviour
的类)。
- using System.Collections;
- using UnityEngine;
- using UnityEditor;
-
- // 这是你要为其创建自定义编辑器的组件
- [AddComponentMenu("MyComponent")]
- public class MyComponent : MonoBehaviour
- {
- public int someValue = 0;
- public bool isBool;
- // ... 其他组件字段 ...
- }
-
- // 自定义编辑器类,用于编辑MyComponent
- [CustomEditor(typeof(MyComponent))]
- public class MyComponentEditor : Editor
- {
- // 获取当前被编辑的MyComponent实例
- private MyComponent myTarget;
-
- // 当编辑器被创建时调用
- void OnEnable()
- {
- // 获取当前编辑的对象
- myTarget = (MyComponent)target;
- }
-
- // 在Inspector窗口中绘制自定义UI
- public override void OnInspectorGUI()
- {
- // 绘制默认的组件字段
- DrawDefaultInspector();
-
- // 添加自定义的编辑器GUI
-
- GUILayout.Space(10); // 添加一些间距
- EditorGUILayout.LabelField("自定义编辑器扩展", EditorStyles.boldLabel);
-
- // 添加一个字段的自定义编辑器
- myTarget.someValue = EditorGUILayout.IntField("自定义值", myTarget.someValue);
-
- // 确保更改被应用
- if (GUI.changed)
- {
- EditorUtility.SetDirty(myTarget); // 标记目标为已更改
- }
- }
- }

通常情况下,MonoBehaviour 中的代码只在游戏运行时(即按下播放按钮后)才会被执行。但是,为脚本添加[ExecuteInEditMode]特性后在 Unity 编辑器的非运行状态下也能执行某些逻辑。
使用[ExecuteInEditMode]特性后,Unity 会在编辑器中自动调用该 MonoBehaviour 的 Update()
、OnValidate()
和其他在运行时调用的函数(除了 Awak()、Start()外,因为 Awak()、Start() 只在游戏运行时被调用一次)。这对于开发需要在编辑器中即时反馈的自定义编辑器工具或脚本非常有用,比如自定义的着色器编辑器、地形编辑器、或是需要在编辑器中预览效果的脚本。
[ExecuteInEditMode]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。