You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中判断SerializedProperty是否属于数组及结构体编辑器显示适配

Unity编辑器中Stat结构体的差异化显示与数组元素判断方案

一、判断SerializedProperty是否为数组元素

要判断某个SerializedProperty是不是数组里的元素,有两种简单实用的方法:

  • 方法1:检查属性路径
    数组元素的路径里必然包含.Array.data[索引]这种格式(比如myStats.Array.data[2]),直接通过字符串匹配就能判断:
    bool isArrayElement = property.path.Contains(".Array.data[");
    
  • 方法2:检查父属性类型
    数组元素的父属性一定是数组类型,所以可以直接判断父属性的类型:
    bool isArrayElement = property.parent != null && property.parent.isArray;
    

二、自定义PropertyDrawer实现差异化显示

创建一个StatDrawer类,继承自Unity编辑器的PropertyDrawer,重写绘制逻辑,根据是否为数组元素调整显示样式:

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(Stat))]
public class StatDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // 判断当前属性是否属于数组元素
        bool isArrayElement = property.parent != null && property.parent.isArray;

        // 获取结构体里的key和value属性
        var keyProp = property.FindPropertyRelative("key");
        var valueProp = property.FindPropertyRelative("value");

        if (isArrayElement)
        {
            // 数组元素:不显示标签,直接并排绘制key和value输入框
            var keyRect = new Rect(position.x, position.y, position.width / 2 - 5, position.height);
            var valueRect = new Rect(position.x + position.width / 2 + 5, position.y, position.width / 2 - 5, position.height);
            
            EditorGUI.PropertyField(keyRect, keyProp, GUIContent.none);
            EditorGUI.PropertyField(valueRect, valueProp, GUIContent.none);
        }
        else
        {
            // 单个字段:显示字段标签,再绘制带小标签的key和value
            EditorGUI.BeginProperty(position, label, property);
            // 绘制字段的主标签(比如变量名)
            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
            
            // 分割区域给key和value
            var keyRect = new Rect(position.x, position.y, position.width / 2 - 5, position.height);
            var valueRect = new Rect(position.x + position.width / 2 + 5, position.y, position.width / 2 - 5, position.height);
            
            EditorGUI.PropertyField(keyRect, keyProp, new GUIContent("Key"));
            EditorGUI.PropertyField(valueRect, valueProp, new GUIContent("Value"));
            EditorGUI.EndProperty();
        }
    }

    // 固定行高,和默认属性保持一致
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return EditorGUIUtility.singleLineHeight;
    }
}

三、实际效果

  • 当Stat作为单个非数组字段时:
    会显示你定义的变量名作为主标签,后面跟着带"Key"、"Value"小标签的输入框,整体是一行布局。
  • 当Stat作为数组元素时:
    不会显示默认的"Element X"标签,直接并排展示key和value的输入框,让数组列表更紧凑整洁。

内容的提问来源于stack exchange,提问作者user3915050

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:15:39