Serialization

m

Serialization

Unity features are built ontop of the serialization system:

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

Be public

or have [SerializeField] attribute

Not be

static

const

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. (new in Unity4.5)

References to objects that derive from UntiyEngine.Object

Primitive data types (int,float,double,bool,string,etc)

Array of a fieldtype we can serialize

List<T> of a fieldtype we can serialize

what are these situations where the serializer behaves differently from what I expect?

Custom classes behave like structs

class Animal{
public string name;
}

class MyScript : MonoBehaviour{
public Animal[] animals;
}

If you populate the animals array with three references to a single Animal object, in the serializationstream you will find 3 objects.

When it’s deserialized, there are now three different objects.

If you need to serialize a complex object graph with references, you cannot rely on Unity’s serializer doing that all automagically for you, and have to do some work to get that object graph serialized yourself.

No support for null for custom classes

class Test : MonoBehaviour{
public Trouble t;
}

[Serializable]
class Trouble{
public Trouble t1;
public Trouble t2;
public Trouble t3;
}

Assets, Objects and serialization

1.1. Inside Assets and Objects

one-to-many relationship between Assets and Objects

any given Asset file contains one or more Objects

Assets

file on disk, stored in the Assets folder of a Unity project

Some Assets contain data in formats native to Unity, such as materials.

Other Assets need to be processed into native formats, such as FBX files.

UnityEngine.Objects

set of serialized data collectively describing a specific instance of a resource

any type of resource which the Unity Engine uses

such as a mesh, a sprite, an AudioClip or an AnimationClip

Objects are subclasses of the UnityEngine.Object base class

While most Object types are built-in, there are two special types

ScriptableObject

provides a convenient system for developers to define their own data types

can be natively serialized and deserialized and manipulated in the Inspector window

MonoBehaviour

a wrapper that links to a MonoScript

MonoScript is an internal data type that Unity uses to hold a reference to a specific scripting class within a specific assembly and namespace

The MonoScript does not contain any actual executable code.

1.2. Inter-Object references

(references)

All UnityEngine.Objects can have references to other UnityEngine.Objects