Skip to content

Script Serialization

antfarmar edited this page Nov 20, 2015 · 7 revisions

Script Serialization

Manual entry

Serialization of “things” is at the very core of Unity.

What does a field of my script need to be in order to be serialized?

  • be public, or have [SerializeField] attribute
  • not be static
  • not be const
  • not be readonly
  • the fieldtype needs to be of a type that we can serialize.

Which fieldtypes can we serialize?

  • custom non abstract classes with [Serializable] attribute.
  • custom structs with [Serializable] attribute. (Added in Unity 4.5)
  • references to objects that derive from UnityEngine.Object
  • primitive data types (int, float, double, bool, string, etc.)
  • array of a fieldtype we can serialize
  • List of a fieldtype we can serialize

Further Reading & References:

Scripting Reference

Unity will serialize all your script components, reload the new assemblies, and recreate your script components from the serialized verions. This serialization does not happen with .NET's serialization functionality, but with an internal Unity one.

The serialization system used can do the following:

  • CAN serialize public nonstatic fields (of serializable types)
  • CAN serialize nonpublic nonstatic fields marked with the [SerializeField] attribute.
  • CANNOT serialize static fields.
  • CANNOT serialize properties.

Your field will only serialize if it is of a type that Unity can serialize:

Serializable types are:

  • All classes inheriting from UnityEngine.Object, for example GameObject, Component, MonoBehaviour, Texture2D, AnimationClip.
  • All basic data types like int, string, float, bool.
  • Some built-in types like Vector2, Vector3, Vector4, Quaternion, Matrix4x4, Color, Rect, LayerMask.
  • Arrays of a serializable type
  • List of a serializable type)
  • Enums
  • Structs

Note: if you put one element in a list (or array) twice, when the list gets serialized, you'll get two copies of that element, instead of one copy being in the new list twice.

Hint: Unity won't serialize Dictionary, however you could store a List<> for keys and a List<> for values, and sew them up in a non serialized dictionary on Awake(). This doesn't solve the problem of when you want to modify the dictionary and have it "saved" back, but it is a handy trick in a lot of other cases.

Clone this wiki locally