Unity field containing ScriptableObject not serializing

Viewed 2443

I'm having a problem getting a field to serialize properly.

It links to a custom type which extends ScriptableObject. A custom editor is creating the instance of this object, and it's not being saved as an asset file. It's my understanding at the moment that you can do this - Unity should be saving this data into the scene instead of the project automatically.

First up, the MonoBehaviour class. This I've set up to hold an instance of Bar and a string just to double check the serialization is working at all. I use fields with exposing properties, so I've done it here as well as I know reflection is involved.

public class Foo : MonoBehaviour
{
    [SerializeField]
    private Bar bar;

    [SerializeField]
    private string check;

    public Bar Bar { get { return this.bar; } set { this.bar = value; } }
}

Next, the ScriptableObject based Bar class. This is the class I want to instance and link, but not save as an asset file.

[Serializable]
public class Bar : ScriptableObject
{
    [SerializeField]
    private string data;
}

Finally, a CustomEditor which allows me to create and link an instance of Bar:

[CustomEditor(typeof(Foo))]
public class StreamableResourceTestEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Link unsaved Bar asset"))
        {
            Bar bar = ScriptableObject.CreateInstance<Bar>();
            bar.name = "Unsaved asset";

            Foo foo = (Foo)this.target;
            foo.Bar = bar;

            EditorUtility.SetDirty(foo);
        }
    }
}

Before running, having entered data and pressed the button:

Before Running

During running:

enter image description here

After running:

enter image description here


The string serializes properly.

However, the ScriptableObject fails to be serialized into the runtime data. Not only that, after running the project the instance is still linked, but has lost it's type!

Does anyone know what the problem is with this?


Update:

Just tested this without extending Bar from ScriptableObject, and creating it as a normal C# instance instead of with ScriptableObject.CreateInstance<Bar> and it all works as expected.

Whatever the problem is, it relates to extending from ScriptableObject.

0 Answers
Related