【第三章自定义检视面板_创建自定义编辑器_如何创建自定义PropertyDrawer(9/9)】

3.2.3 如何创建自定义PropertyDrawer

上面二个unity给我们提供的,我们可以自定义Attrbute去实现自己想要的效果。这里举一个自定义PropertyDrawer的例子。假设我们有一个属性用于表示时间(以秒为单位)

三步走

1.定义特性类 (PropertyAttribute)

csharp 复制代码
using System;
using UnityEngine;

/*
 命名机制:
XXXAttribute 类 → [XXX] 标记
Unity 自动完成后缀匹配
 
 */
[AttributeUsage(AttributeTargets.Field)]
public class TimeAttribute : PropertyAttribute
{
    
}

2.创建 PropertyDrawer

csharp 复制代码
using UnityEditor;
using UnityEngine;
using System;

[CustomPropertyDrawer(typeof(TimeAttribute))]
public class TimePropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (property.propertyType == SerializedPropertyType.Float)
        {
            property.floatValue = EditorGUI.FloatField(new Rect(position.x, position.y, position.width * 0.6f, position.height), label, property.floatValue);
            EditorGUI.LabelField(new Rect(position.x + position.width * 0.6f, position.y, position.width * 0.4f, position.height), GetTimeFormat(property.floatValue));
        }
    }

    private string GetTimeFormat(float time)
    {
       //取整获得总共的秒数
       int l = Convert.ToInt32(time);
        //计算小时、分钟、秒
        int hour = l / 3600;
        int minute = (l % 3600) / 60;
        int second = l % 3600 %60;
        return string.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
    }
}

3. 使用自定义 PropertyDrawer

csharp 复制代码
using UnityEngine;

public class PropertyDrawerExample : MonoBehaviour
{

    //时间字段(自定义特性),这里是为什么是Time,请看第一步
    [Time, SerializeField]
    private float duration = 596f;

    [Time, SerializeField]
    private int delay = 2;
}

效果图

实际上,书上在本小节还举了二个例子,一个是为 Unity 中的 Color 类型属性提供了​​增强版的 Inspector 界面​​,在保留标准颜色选择器的基础上,添加了十六进制颜色输入和透明度独立控制功能,另一个是为 Unity 中的 Sprite 类型属性提供了​​增强版的 Inspector 显示​​,在保留标准精灵选择功能的基础上,添加了大型预览图和精灵名称显示功能。

下面给出链接,有需要还可以看看

1.扩展Color
2.扩展Sprite
相关推荐
SmalBox4 小时前
【渲染流水线】[几何阶段]-[图元装配]以UnityURP为例
unity·渲染
QL.ql5 小时前
vscode的wsl环境,ESP32驱动0.96寸oled屏幕
ide·vscode·编辑器
霜绛16 小时前
Unity:GUI笔记(一)——文本、按钮、多选框和单选框、输入框和拖动条、图片绘制和框绘制
笔记·学习·unity·游戏引擎
谷宇.18 小时前
【Unity3D实例-功能-移动】角色行走和奔跑的相互切换
游戏·unity·c#·unity3d·游戏开发·游戏编程
广州华锐视点18 小时前
论郑和下西洋元素融入课件编辑器的意义与影响
编辑器
Dawn·张18 小时前
UE小:编辑器模式下「窗口/鼠标不在焦点」时仍保持高帧率
编辑器
17岁的勇气19 小时前
Unity Shader unity文档学习笔记(十九):粘土效果,任意网格转化成一个球(顶点动画,曲面着色器)
笔记·学习·unity·图形渲染·顶点着色器·曲面着色器
ayaya_mana1 天前
Notepad--:国产跨平台文本编辑器,Notepad++ 的理想替代方案
linux·windows·macos·编辑器·notepad·notepad--
QL.ql1 天前
(一)vscode搭建espidf环境
ide·vscode·编辑器
benben0441 天前
《Unity Shader入门精要》学习笔记一
unity·shader