Need to serialize a Monobehaviour Class

I need to serialize a class that inherits from Monobehaviour in order to save my game data, but I'm getting an error:

SerializationException: Type UnityEngine.MonoBehaviour in assembly UnityEngine, Version=0.0.0.0, Culture=neutral is not marked as serializable.

I heard that Monobehaviour was serializable (that would be a glaring limitation in the engine if it wasn't). I've marked all my custom classes as serializable, but is there another command I need in order to make Monobehaviour serializable?

MonoBehaviour isn't serializable no - but that's probably a good thing. You'd be able to serialize it, but not deserialize. You can't just do new MonoBehaviourDerivative() to create a monobehaviour, it's got to be done with AddComponent, meaning you'd need completely different deserialization for it anyway

What I would do is use the Memento pattern - an object you have an instance of from your script which is serializable itself, which keeps all the data for the object

Makes it rather easy to serialize and deserialize your data.

Alternatively, there is a third party addon called EZGUI, which serializes monobehaviours by their public properties and fields

For everyone else hopelessly confused… (this works as of 8/25/2016.)

Step #1. Create an Object that is to be serializable; Add the following to the top of your code

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

Step #2. next add [Serialisable] just above the “Public class myObject”

Step #3. Remove “MonoBehavior”, so it doesn’t inherit from that

Step #4. Instance your object from another class that inherits from MonoBehavior, and place that script and object in the heirarchy somewhere of your project like you would any other.

MSDN has more information Object Serialization in .NET | Microsoft Learn

Step #5. Also… check your work. When the file is written you should inspect it with a hex editor, it will write to a file in your root directory unless you specified otherwise.

If you have questions let me know.