Serialize ScriptableObject without creating an asset out of it?

Is it possible to do something like this?

public class MyComponent : MonoBehaviour
{

    public MyScriptable myScriptable;

    public void OnValidate()
    {
        if (myScriptable == null)
        {
             myScriptable = ScriptableObject.CreateInstance<MyScriptable>();      
        }
    }

}

public class MyScriptable : ScriptableObject
{

    public int MyVar1;
    public string MyVar2;

}

I tried this but am getting a “Type Mismatch” error in Unity.

Well, yes and no, it is certainly possible, but I don’t see why you would want to do that and why you would want it to be a scriptable object in that case.

You can use XML or binary serialization with .NET libraries, or write your own serialization, but you still have to store the serialized data somewhere.

The reason is that my Scriptable Object inherits from a base class and can be used by itself but is also sometimes embedded inside MonoBehaviours. It would be quite lame that a Unity Object couldn’t be serialized normally.

Except that CreateInstance(); should be ScriptableObject.CreateInstance();, the code works as intended.

You’re probably doing something funky in the inheritance that’s breaking things.

Sorry, I free-typed the code above but have you tried it yourself?

Here’s the package that illustrates the problem:
https://expirebox.com/download/09cb7eb3e09281683db83cb544e1f8bc.html

It contains 2 assets: Asset.cs and Asset2.cs. Just create a new Asset from the menu and then watch what happens. There’s no inheritance or nothing.

I tried it myself by copy-pasting your post. It’s a big difference - your post had a MonoBehaviour as the object containing the scriptable, your package has a ScriptableObject as the container.

If you add a ScriptableObject field to a MonoBehaviour, Unity just creates the object as a part of the scene file and dumps it in there, and references it. So that works. But for sub-assets, you have to actually create the asset.

1 Like

So there’s no way to do it for ScriptableObjects like in the package I uploaded?

Pretty sure there’s not, though I could be wrong.

The usual way to do this is to add Asset2 as a sub asset.