- Home /
Serializing a ScriptableObject without creating an asset for 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.
Answer by Bodrp · Apr 26, 2017 at 11:32 PM
I may be completely off-track with my answer. I assumed you wanted to see MyVar1 and MyVar2 in the inspector. If I am wrong, please tell me so I can correct myself.
Just over your MyScriptable class, add the Serializable attribute. Also, MyScriptable must not inherit from ScriptableObject.
Optionally, you can also use the SerializeField attribute on the myScriptable variable instead of the public access modifier to preserve encapsulation (that is if it is only directly used by MyComponent instances).
public class MyComponent : MonoBehaviour
{
[SerializeField] MyScriptable myScriptable;
}
[System.Serializable] // <-- This is what you need.
public class MyScriptable // No need for the ScriptableObject class.
{
public int MyVar1;
public string MyVar2;
}
Once you select the game object having a MyComponent component, it will render as such.

Not inheriting from ScriptableObject is not an option. The reason is that I have an abstract base class and classes deriving from that abstract class so if I stopped inheriting from ScriptableObject I would lose polymorphic serialization.
Do you mean the $$anonymous$$yComponent class would be abstract in the example, or maybe the $$anonymous$$yScriptable class? Or is it some unmentioned other class?
The $$anonymous$$yScriptable class would be abstract.
Answer by PizzaPie · Apr 27, 2017 at 12:12 PM
Change the line
myScriptable = CreateInstance<MyScriptable>();
to:
myScriptable = ScriptableObject.CreateInstance<MyScriptable>();
to see the fields of the myScriptable double click on it. Cheers.
Bad answer. It doesn't get serialized. The line was just a typo.
Did you double click it to show you the actual scriptable object? of course it doesn't get serialized on the normal fashion.
Your answer
Follow this Question
Related Questions
CustomEditor for an ScriptableObject asset only works after recompile. 1 Answer
Calling a derived class (Serialized in a Scriptable Object) returns the super class. 1 Answer
A scripted Object has a different layout when loading: scriptable objects and inheritance 1 Answer
Draw scriptable object "inspector" in custom window (EditorWindow) 1 Answer