序列化和反序列化Unity3D MonoBehaviour脚本 [英] Serialize & Deserialize Unity3D MonoBehaviour script

查看:505
本文介绍了序列化和反序列化Unity3D MonoBehaviour脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:从Monobehaviour继承的类无法序列化.

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

前提:一种保存MonoBehaviour脚本的数据(变量/字段及其值)的方法,以便可以对其进行序列化,然后再次反序列化,然后使用此数据填充"相应的MonoBehaviour脚本的变量/字段值

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.

到目前为止已尝试:

  1. 具有一个可序列化的包装器/容器"类,该类具有与MB脚本相同的字段,但不继承自MB.效果很好,但是每个MV脚本都需要它自己的包装器类和包装器功能.
  2. 序列化List<FieldInfo>并用MB的字段填充它...起作用30%;
    • 添加了FieldInfos,但类型错误,并且
    • 反序列化时,由于需要一个类的实例而无法访问它们的值,但是只有一个列表可用
  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.

推荐答案

没有简单的方法可以使用.NET内置的BinaryFormatter序列化MonoBehaviour.您可以考虑以下几种选择:

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

  1. 使用 Memento Patter .那就是(或多或少)您尝试使用包装器实现的. Momento假定保存和恢复对象的内部状态,因此序列化是一种技术.
  2. 使用Unity序列化,方法是声明以下方法:

  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 Serialize(){}

void Deserialize(){}

void Deserialize(){}

在MonoBehaviour脚本中,因此在方法中,您将选择要序列化/反序列化的属性/字段.

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

有一个有趣的框架,源代码位于 GitHub 上.它具有一个自定义的序列化框架,可让您序列化几乎所有内容(不仅是单行为).我从未使用过它,

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.

这篇关于序列化和反序列化Unity3D MonoBehaviour脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆