Serialization Error

I get an error whenever I try and use the saveTerrainDatabase() method in my code below.

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

I’ve read from another question posted on unity answers that classes inheriting from monobehavior can be serialized (which I have done).

using UnityEngine;
using System.Collections;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;

[System.Serializable]
public class terrainManager : MonoBehaviour {

	public chunkManager[] chunks = new chunkManager[100];
	
	private fileManager fm = new fileManager();
	private bool isDataEncrypted = false;

	public void Awake()
	{
		fm.initialize();
		fm.createDirectory("Database"); //creates a file directory if one does not exist
		if(fm.checkFile("Database/Terrain.dat") == true) //if file exists, use it
		{
			Debug.Log("File found");
			loadTerrainDatabase();
		}
		else //else create a new file if there isn't one
		{
			Debug.Log("Creating new file");
			fm.createFile("Database","Terrain","dat","empty terrain file",isDataEncrypted);
		}
	}

	public void loadTerrainDatabase()
	{

	}

	public void saveTerrainDatabase()
	{
		BinaryFormatter bf = new BinaryFormatter();
		MemoryStream ms = new MemoryStream();
		bf.Serialize(ms,this);
		fm.updateFile("Database","Terrain","dat",Convert.ToBase64String(ms.GetBuffer()),isDataEncrypted, false);
	}

The error exception highlights line 41 whenever I double click the error in the console.

You cannot serialize MonoBehaviours with .NET serialization, they are serialized by Unity when it creates scenes, prefabs and Asset Bundles. This is because MonoBehaviour does not have a constructor anything can access - they have to be attached to a GameObject.

You could use Unity Serializer’s SerializeForDeserializeInto and DeserializeInto which will allow you to save the variables of the class and then restore them to another instance of that class in future. Or you could make your class a normal one and just have a reference to it in your MonoBehaviour.

Thanks for the link on the live training.

I started to experiment with saving to a byte and loading back using CoAdjoint’s video:


This method works really well. It serialize/deserialize the entire class structure and no need for the explicit saving of each individual variable. wow.