Serialization with custom editor, prefab not saving (again)

Hi,
I noticed this question has been raised a lot of times, but I didn’t see a solution that works for me, maybe I missed it.

I’ve got a MonoBehaviour holding some data structure and made a dedicated editor for that behaviour. Modifying the data structure through the editor on a scene object works nicely, but when creating a prefab with this behaviour attached to it, modifications of the data structure are not saved upon scene load.

Here are my scripts:

The behaviour:

using UnityEngine;
 
public class NewComponent : MonoBehaviour
{
    public NewDataStructure data;
}

The data structure:

using UnityEngine;
using System;
 
[Serializable]
public class NewDataStructure : ScriptableObject
{
    public int value;
}

The editor:

using UnityEngine;
using UnityEditor;
 
[CustomEditor(typeof(NewComponent))]
public class NewEditor : Editor
{
    public override void OnInspectorGUI()
    {
        NewComponent component = target as NewComponent;
        if (component.data==null)
            component.data = (NewDataStructure) ScriptableObject.CreateInstance(typeof(NewDataStructure));
       
        component.data.value = EditorGUILayout.IntField("dataValue", component.data.value);
       
        EditorUtility.SetDirty(component);
        EditorUtility.SetDirty(component.data);
    }
}

Can you please help me with this problem ?

You should use a SerializedObject to modify values of a serialized object.

You don’t even have to create one manually. Unity now creates one automatically for you:
Editor.serializedObject. The SerializedObject also allows multi objects editing if you need it.

See also SerializedProperty