问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Unity自定义Inspector属性名特性以及特性自定义布局问题

创作时间:
作者:
@小白创作中心

Unity自定义Inspector属性名特性以及特性自定义布局问题

引用
CSDN
1.
https://m.blog.csdn.net/m0_68267247/article/details/144749497

在Unity开发中,Inspector面板的属性名默认显示为英文,这对于中文开发者来说不够友好。本文将介绍如何通过自定义Inspector属性名特性,实现属性名的本地化显示,并解决自定义布局问题。

前言:

在Unity中编辑属性时,默认会显示属性的英文名称。如果想要将其改为中文显示,但又不能改变属性名,那么自定义特性是一个很好的解决方案。

一、自定义特性

这一块没有什么要多说的,就是自定义特性

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class FieldNameAttribute : PropertyAttribute
{
    internal string Name { get; private set; }
    public FieldNameAttribute(string name)
    {
        Name = name;
    }
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(FieldNameAttribute))]
public class FieldNameAttributeDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.PropertyField(position, property, new GUIContent((attribute as FieldNameAttribute).Name), property.hasChildren);
    }
}
#endif  

二、布局问题

这样写其实已经完成了基本效果,如图:

但是可以看到,虽然定义了属性,但我们没有处理其可见子元素的布局。为了解决这个问题,我们需要重写PropertyDrawer中的GetPropertyHeight函数:

public class FieldNameAttributeDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.PropertyField(position, property, new GUIContent((attribute as FieldNameAttribute).Name), property.hasChildren);
    }
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        float baseHeight = base.GetPropertyHeight(property, label);
        if (property.isExpanded)
        {
            if (property.propertyType == SerializedPropertyType.Generic)
            {
                return baseHeight + EditorGUIUtility.singleLineHeight * property.CountInProperty();
            }
        }
        return baseHeight;
    }
}  

经过优化后的效果如下图所示:

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号