SerializedProperty label changes when expanded

Hello, I have this problem where serialized property’s label changes when expanded and I can’t figure out why.

Here is the example code:

using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

[CreateAssetMenu(menuName = nameof(ScriptableObject) + "/" + nameof(Test))]
public class Test : ScriptableObject
{
    public CustomObject<ComplexObject> CustomObject;
}

[Serializable]
public class ComplexObject
{
    public int a;
    public float b;
}

[Serializable]
public class CustomObject<T>
{
    public T Value;
}

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(CustomObject<>))]
public class CustomObjectDrawer : PropertyDrawer
{
    private const string k_ValuePropertyKey = "Value";

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        SerializedProperty valueProperty = property.FindPropertyRelative(k_ValuePropertyKey);
        EditorGUILayout.PropertyField(valueProperty, label);

        EditorGUI.EndProperty();
    }
}
#endif

And here are screenshots:


As you can see the label changes when field is expanded. I can’t undestand why it happens, I guess the EditorGUI.PropertyField method draws something like base implementation for expanded fields.
How can I fix it so it will display the label I want?
Many thanks!

Don‘t use IMGUI anymore for editor GUI. Replace it with UI Toolkit and you‘ll be in control of the GUI, not vice versa.

1 Like

Well I figured it out myself. You can just create new GUIContent from label passed to OnGUI as parameter and use it as your label. Or I think most preferable way is to write return value of EditorGUI.BeginProperty method to label, i.e:


label = EditorGUI.BeginProperty(position, label, property);

Code:

using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

[CreateAssetMenu(menuName = nameof(ScriptableObject) + "/" + nameof(Test))]
public class Test : ScriptableObject
{
    public CustomObject<ComplexObject> CustomObject;
}

[Serializable]
public class ComplexObject
{
    public int a;
    public float b;
}

[Serializable]
public class CustomObject<T>
{
    public T Value;
}

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(CustomObject<>))]
public class CustomObjectDrawer : PropertyDrawer
{
    private const string k_ValuePropertyKey = "Value";

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        label = EditorGUI.BeginProperty(position, label, property);

        SerializedProperty valueProperty = property.FindPropertyRelative(k_ValuePropertyKey);
        EditorGUILayout.PropertyField(valueProperty, label);

        EditorGUI.EndProperty();
    }
}
#endif
1 Like