Cannot serialize System.Type field

I’ve run into an issue serializing a System.Type field.

in a scriptable object, I have the following code:

using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;


[Serializable]
public class TypeStorage : ScriptableObject
{
	[SerializeField]
	public Type type;
	[SerializeField]
	public string typeName;

	protected void OnEnable() { hideFlags = HideFlags.HideAndDontSave; }

	public virtual void OnGUI()
	{
		if(type != null)
			GUILayout.Label(type.ToString(), EditorStyles.whiteLabel);
		else
			GUILayout.Label("no type set");
		
		GUILayout.Label(typeName);
	}
}

the typeName field serializes properly, but the Type field gets lost on reload.
Is there a way around this? I’m trying to avoid string comparisons for type verification.

I have created a serializable wrapper for System.Type along with a couple of attributes and property drawer for editor interfaces:

https://bitbucket.org/rotorz/classtypereference-for-unity

Unity can only serialize a few types which are listed here (Serializable types) The only way you have is to use the string representation of the Type. Make sure you use the AssemblyQualifiedName.

Since the question got already bumped I like to add that i’ve written a System.Type wrapper some time ago. It should support any System.Type, even generic types. I’ve also made a serializable method info which depends on the SerializableType. It basically stores the whole type definition in a compact binary format which is then stored as byte array

You can try this wrapper for newer versions of Unity since numberkruncher’s one doesn’t work properly in Unity 2019+:
https://github.com/SolidAlloy/ClassTypeReference-for-Unity