【第三章自定义检视面板_创建自定义编辑器_如何创建自定义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
相关推荐
-To be number.wan9 小时前
编译原理第三章:编译器是怎么“认字“的?——词法分析全解析
学习·编辑器
Madokaly10 小时前
DOTween的Vector3Plugin
unity
gzkuijing14 小时前
MDI1PRD23B7‑EQ|Novanta IMS一体化RS-485/422步进电机参数、选型要点与典型应用
人工智能·机器学习·编辑器
一梭键盘任平生20 小时前
Shader入门笔记2
unity
点心的游戏开发世界1 天前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#
点心的游戏开发世界1 天前
Unity C# 脚本学习笔记:泛型
学习·unity·c#
晚风叙码2 天前
Linux(三)apt/yum 软件安装与 vim 编辑器入门指南
linux·编辑器·vim
民乐团扒谱机2 天前
【超详细】PyQt6 实现 AU 风格波形图编辑器:多级缩放与采样点逐级渲染,附全过程代码
开发语言·python·编辑器·pyqt·audition·时域·频谱图
谁刺我心2 天前
【vscode问题】远程remote cpptools导致linux板子cpu爆炸问题
ide·vscode·编辑器
微三云生态系统架构师-彭丹3 天前
任务卷轴积分系统架构设计:从任务状态机到合规风控的完整实现
unity·系统架构·游戏引擎