Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize & Deserialize Unity3D MonoBehaviour script

Background: Classes that inherit from Monobehaviour can't be serialized.

Premise: A way to save the data (variables/fields and their values) of a MonoBehaviour script so it can be serialized, and deserialize it again and use this data to "fill in" a corresponding MonoBehaviour script's variable/field values.

Tried so far:

  1. Having a serializable "wrapper/container" class that has the same fields as the MB script, but does not inherit from MB. Works nicely but every MV script needs it's own wrapper class and it's own wrapping function.
  2. Serializing a List<FieldInfo> and fill it with the MB's fields... Works 30%;
    • The FieldInfos get added but are of the wrong Type, and
    • When deserialzing their values can't be accessed because an instance of a class is needed, but only a list is available

I feel like it can't be that hard but my Reflection skills and related are limited but seeing as saving/loading is a rather common feature I hope there is either someone who did it or someone who can point me in the right direction.

like image 271
Cherno Avatar asked Oct 20 '22 14:10

Cherno


2 Answers

There is no easy way to serialize a MonoBehaviour using a BinaryFormatter built in .NET. There are a few options you can consider:

  1. Using a Memento Patter. That is (more or less) what you have tried to achieve using a wrapper. Momento assumes a saving and restoring internal state of objects, so serialization is one of techniques.
  2. Using Unity Serialization, by declaring the methods:

    void Serialize(){}

    void Deserialize(){}

    In your MonoBehaviour script, so within the methods you will choose the properties/fields you want to serialize/deserialize.

  3. There is an interesting framework, source code is on GitHub. It has a custom serialization framework that lets you serialize almost anything (not only monobehaviors). I have never used it, here is the forum page on Unity3d forum, I believe it's worth a look.

like image 186
codingadventures Avatar answered Oct 22 '22 23:10

codingadventures


The answer to the question is: ScriptableObject. That's what they're for.

Put your variables in a ScriptableObject and Unity will handle the serialisation and give you a custom editor and other nice features. Recommended.

like image 40
david.pfx Avatar answered Oct 22 '22 21:10

david.pfx