Serialize & Deserialize Unity3D MonoBehaviour scri

2019-05-07 07:22发布

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.

1条回答
老娘就宠你
2楼-- · 2019-05-07 07:52

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.

查看更多
登录 后发表回答