Unity自定义编辑器:如何为EditorGUI.PropertyField设置初始值?
给Unity自定义PropertyDrawer中的PropertyField设置初始值的解决方案
核心思路
要给Name属性设置初始值,不需要用EditorGUI.LabelField替代(会破坏布局),直接通过初始化序列化属性值的方式实现,既能保留PropertyField的可编辑性,又能维持Inspector布局正常。
方案1:在数据类中直接初始化(最简单)
在你的InfoList序列化类里,直接给Name字段赋初始值,编辑器加载时会自动读取这个默认值:
[System.Serializable] public class InfoList { public string Name = "默认列表名称"; // 直接设置初始值 public List<YourListItemType> List; }
方案2:在PropertyDrawer中动态设置初始值
如果需要根据其他属性(比如列表数量)动态生成初始值,可在OnGUI方法中判断Name是否为空,为空则赋值,再正常绘制PropertyField:
修改你的InfoListDrawer代码:
[CustomPropertyDrawer(typeof(InfoList))] public class InfoListDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); float nameWidth = 100f; int indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; // 获取Name属性 SerializedProperty nameProp = property.FindPropertyRelative("Name"); // 判断是否为空,设置初始值 if (string.IsNullOrEmpty(nameProp.stringValue)) { // 可自定义初始值,比如根据列表数量生成 SerializedProperty listProp = property.FindPropertyRelative("List"); nameProp.stringValue = listProp.arraySize == 0 ? "空列表" : $"列表({listProp.arraySize}项)"; // 应用修改到序列化对象 property.serializedObject.ApplyModifiedProperties(); } float nameHeight = EditorGUI.GetPropertyHeight(nameProp); Rect namePosition = new (position.x, position.y + (position.height - nameHeight) / 2f, nameWidth, nameHeight); EditorGUI.PropertyField(namePosition, nameProp, GUIContent.none); Rect listPosition = new (position.x + nameWidth + 20, position.y, position.width - nameWidth - 20, position.height); SerializedProperty listProperty = property.FindPropertyRelative("List"); EditorGUI.PropertyField(listPosition, listProperty, true); EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { SerializedProperty listProperty = property.FindPropertyRelative("List"); return EditorGUI.GetPropertyHeight(listProperty, true); } }
为什么EditorGUI.LabelField会破坏布局?
LabelField是只读控件,它的布局计算逻辑和PropertyField(可编辑输入框)完全不同:
PropertyField会自动适配输入框的高度、边距,和Inspector的整体布局规则对齐;- 强行用
LabelField替换,会打破Unity Inspector的自动布局流,导致控件错位、高度计算错误。
而直接修改序列化属性的初始值再用PropertyField绘制,完全遵循Unity的布局规则,不会出现布局问题。
内容的提问来源于stack exchange,提问作者Yusuf Tahir Orhan
相关产品推荐
相关产品推荐

