- Home /
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.
Thanks!
Answer by Xarbrough · Sep 20, 2015 at 08:06 AM
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.
2021 update: after following links to more recent repositories successively, I found the modern equivalent: https://github.com/SolidAlloy/ClassTypeReference-for-Unity
Answer by IgorAherne · Aug 27, 2015 at 12:45 AM
Short answer: http://answers.unity3d.com/questions/292634/how-to-reference-monobehaviour-in-scriptableobject.html
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: https://www.youtube.com/watch?v=Y2P_9s3KhdU
2) Read the answer and he also links a different thread, read what his comments are saying there: http://answers.unity3d.com/questions/990996/serializable-lists-items-become-nulls.html
3) he links this thread: http://answers.unity3d.com/questions/967840/saving-your-scene-and-location-in-game.html
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)