Serialize a reference to MonoBehaviour type in ScriptableObject

Is there a way to store a reference to a MonoBehaviour type in a ScriptableObject asset, so that I can AddComponent said type at runtime? There used to be an overload of AddComponent that takes a string “classname”, but it’s deprecated now, so how can I get a reference to the type I need from my ScriptableObject asset?

I have a set of ScriptableObject levels, which I use to load certain data like “level time limit” etc. At runtime, I want to add specific behaviour to my existing level class. I know this sounds, like all specific functions should inherit from “BaseLevel” and then override their behaviour, which would work, but then I would have to create as many prefabs as I have behaviours. I already have my set of ScriptableObjects, so I would like to actually reference those scripts in my SOs, instead of creating a new set of prefabs and then linking both.


Short answer: How to reference MonoBehaviour in ScriptableObject? - Questions & Answers - Unity Discussions

Hardcore (but possible way):
If you want to serialize unity’s internal stuff you will have to go through tornment of BinaryFormatter (2-3 days of learning)

I found an excellent post about Surrogates which are used to serialize unity’s Unserializable Vector3s and transforms, etc.

If you spend time reading it’s invaluable
here you go:

  1. Binary Serialization intro:

  2. Read the answer and he also links a different thread, read what his comments are saying there:
    " Binary Save" Stuff - Workaround for Vector3 Serialization - Questions & Answers - Unity Discussions

  3. he links this thread:
    Saving your scene and location in game? - Questions & Answers - Unity Discussions

After that, you will be able to flush binary data into scriptable object and restore it backwards to interact with the scene.
The data you cant serialze via binary serializator(Vector3s, Transform, GameObjects ) will have work arrounds shown in steps 2) and 3)

Sorry to answer my own question, but I found the perfect solution here: ClassTypeReference by Rotorz

@IgorAherne: Thanks for your answer. Interesting reads and generally good information, but I didn’t really get anything working until I found Rotorz’ solution, which did exactly what I wanted.