How to automatically expanp properties with the inspector?

image
I have a Scriptable Object with a struct property. How can I make it so that whenever this Scriptable Object is viewed in an inspector that the struct property “data” is automatically expanded?

Unity doesn’t automatically serialize nested structs or classes in the inspector, but you can achieve a similar result using a custom property drawer. Here’s an example of how you can do it:

Assuming you have a ScriptableObject with a struct property like this:

using UnityEngine;

[System.Serializable]
public struct MyStruct
{
    public int field1;
    public string field2;
}

[CreateAssetMenu(fileName = "MyScriptableObject", menuName = "Custom/MyScriptableObject")]
public class MyScriptableObject : ScriptableObject
{
    public MyStruct data;
}

Now, create a custom property drawer for MyStruct. You need to create a folder named “Editor” in your “Assets” directory and put the following script inside it:

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(MyStruct))]
public class MyStructDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        // Draw the default property field
        EditorGUI.PropertyField(position, property, label, true);

        // If the property is expanded, draw the fields individually
        if (property.isExpanded)
        {
            EditorGUI.indentLevel++;
            position.y += EditorGUIUtility.singleLineHeight;

            SerializedProperty field1 = property.FindPropertyRelative("field1");
            SerializedProperty field2 = property.FindPropertyRelative("field2");

            EditorGUI.PropertyField(position, field1);
            position.y += EditorGUIUtility.singleLineHeight;
            EditorGUI.PropertyField(position, field2);

            EditorGUI.indentLevel--;
        }

        EditorGUI.EndProperty();
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        float height = EditorGUI.GetPropertyHeight(property, label, true);

        if (property.isExpanded)
        {
            height += EditorGUIUtility.singleLineHeight * 2;
        }

        return height;
    }
}

This custom property drawer will automatically expand the struct fields when you view the ScriptableObject in the Unity inspector.