Unity扩展编辑器功能的特性

1.添加分组标题

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

cs 复制代码
[Header("Common Properties")]
public float MouseSensitivity = 5;
public float SmothTime = 0.1f;

void Start()
{
    //Header应用于属性和字段上
}

2.Assets创建功能添加菜单

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

cs 复制代码
[CreateAssetMenu(menuName ="MyCustomMenu/CustomData")]
public class MyCustomData : ScriptableObject
{
    //CreateAssetMenu主要应用于类上
}

3.工具栏添加菜单

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

cs 复制代码
[MenuItem("CustomMenu/CustomFunc")]
public static void MenuCommand()
{
    //MenuItem应用于静态方法(static)上
}

4.添加组件菜单

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

cs 复制代码
[AddComponentMenu("MyCustomMenu/CustomComponent")]
public class MyCustomData : MonoBehaviour
{
    //与继承自MonoBehaviour的类一起使用
}

5.添加字段右键菜单

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

cs 复制代码
[ContextMenuItem("CustomOption", "FuncA")]
public int customValue;

public void FuncA()
{
    //第一个参数为选项名称,第二个参数为被调用的函数的名称
}

6. 组件自定义编辑器

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

cs 复制代码
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); // 标记目标为已更改  
        }
    }
}
相关推荐
浅陌sss12 小时前
Unity中可靠的UDP实现
unity
奔跑的犀牛先生18 小时前
unity学习46:反向动力学IK
unity
幻世界20 小时前
【工具插件类教学】实现运行时2D物体交互的利器Runtime2DTransformInteractor
unity·交互·运行时2d物体交互
音视频牛哥2 天前
Unity实现高性能多实例RTSP|RTMP播放器技术实践
unity·游戏引擎·音视频·实时音视频·大牛直播sdk·rtsp播放器·rtsp player
Artistation Game2 天前
三、Unity基础(主要框架)
游戏·unity·c#·游戏引擎
Edision_li2 天前
DeepSeek教unity------MessagePack-03
unity·messagepack
lalapanda2 天前
Unity学习part2
学习·unity·游戏引擎
CODE_RabbitV2 天前
【快速入门】Unity 常用组件(功能块)
unity·游戏引擎
BuHuaX2 天前
Unity-New Input System
unity·c#·游戏引擎·游戏程序·lucene
Edision_li3 天前
DeepSeek教unity------UI框架
学习·ui·unity·c#