# How to Serialize Objects (Part 1)

This is the second post in Runtime Serialization series. And in the last post, I tried to clear common doubts like What is serialization? Why is it required? How RS works? etc. In this post we will take a look at brief overview of how to serialize objects. We’ve planned to cover this topic in multiple posts, as we felt some content needs understanding about Extensions which will be covered in future posts.

Most of the Unity Developers will be aware about c# based serialization (Binary Formatter). So keeping that in mind, we decided to follow similar structure for RS as it will help users to easily follow our plugin. So its gonna be like a walk in the park, for those who are already familiar with Binary Formatter.

First and foremost, in order to serialize an object it must be [RuntimeSerializable](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serializable_attribute.html) i.e., only instances of class which are marked using [RuntimeSerializable](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serializable_attribute.html) attribute can be serialized/deserialized. An warning is thrown, if you try to serialize a type which doesn’t have [RuntimeSerializable](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serializable_attribute.html) attribute.

Moving on, lets see how to serialize an object. Serialization as we know it, its the process of the converting object data to binary format. So inorder to serialize an object, just pass the object that needs to be serialized. And on finishing serialization it will return the serialization data in Base64 string format. At later point, this serialization data is required for retrieving back formerly serialized object. Following API call needs to be called for serializing [RuntimeSerializable](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serializable_attribute.html) object.

```
public static string Serialize (T _object, string _serializationID = null)
```

Similarly, for retrieving back original object, call the following API with Base64 string format serialization data.

```
public static T DeserializeData (string _serializationDataBase64, string _serializationID = null, T _targetObject = default(T))
```

Now that was easy. But we forgot to mention the properties of an object that needs to be serialized. An object is a collection of properties, some might be holding important information and others might be used for temporary purpose. So selection of properties to be serialized is quite important for keeping serialization data compact as well as for using minimum CPU cycles. Just like C# Binary Formatter, even RS supports two ways of serializing properties of an object. They are:

## Using Attributes

Just apply [RuntimeSerializableField](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serialize_field_attribute.html) attribute to the fields that you want to serialize. Internally RS will make use of Reflection, to find all the fields that have [RuntimeSerializableField](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serialize_field_attribute.html) attribute. And only serializable fields undergo serialization process. So the fields which doesn’t have [RuntimeSerializableField](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serialize_field_attribute.html) attribute won’t be serialized.

If a serialized class contains references to objects of other classes that are marked [RuntimeSerializable](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serializable_attribute.html) then those objects will also be serialized.

The following example demonstrates the serialization of the fields using [RuntimeSerializableField](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serialize_field_attribute.html) attribute.

```
using System.Collections;
using VoxelBusters.RuntimeSerialization;

// Serialization using Attributes
[RuntimeSerializable]
public class Car
{
    #region Fields 

    [RuntimeSerializeField]
    private string m_model;

    [RuntimeSerializeField]
    private int m_wheelCount;

    #endregion

    #region Constructors

    public Car ()
    {}

    public Car (string _model, int _wheelCount)
    {
        this.m_model         = _model;
        this.m_wheelCount    = _wheelCount;
    }

    #endregion
}

public class CarManager 
{
    #region Fields

    private     Car         m_car                = new Car("bmw", 4);
    private     string         m_serializationData    = null;

    #endregion

    #region Methods

    public void Serialize ()
    {
        // Serializing Car instance
        m_serializationData    = RSManager.Serialize&lt;Car&gt;(m_car);
    }

    public void Deserialize ()
    {
        // Deserialization
        m_car                  = RSManager.DeserializeData&lt;Car&gt;(m_serializationData);
    }

    #endregion
}
```

Tip: *By default,* [*RuntimeSerializable*](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serializable_attribute.html) *attribute serializes all the public fields of a serialized object. However you can change this behaviour, by passing override flags to* [*RuntimeSerializable*](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serializable_attribute.html) *attribute.*

## Using IRuntimeSerializable

If a class needs full control of serialization process, then implement [IRuntimeSerializable](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/interface_voxel_busters_1_1_runtime_serialization_1_1_i_runtime_serializable.html) interface. This implementation overrides reflection based serialization process and allows class to handle its own serialization and deserialization.

At the time of serialization RS calls [WriteSerializationData](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/interface_voxel_busters_1_1_runtime_serialization_1_1_i_runtime_serializable.html#ad0d562a5e94e40838224b0a126f87c43) method and you can add the properties to [RuntimeSerializationInfo](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serialization_info.html) that are required to serialize an object. Similary when deserializing, RS calls [ReadSerializationData](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/interface_voxel_busters_1_1_runtime_serialization_1_1_i_runtime_serializable.html#a052bee3d106563961eb5f7d0d7a26756) method. This method supplies [RuntimeSerializationInfo](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/class_voxel_busters_1_1_runtime_serialization_1_1_runtime_serialization_info.html) which can be used to retrieve all the values that were previously added.

In case of inheritance, make sure that derived class calls the interface methods of base class otherwise properties of base class won’t be serialized.

Code example below demonstrates the use of [IRuntimeSerializable](http://voxel-busters-interactive.github.io/Runtime-Serialization/Documentation/DoxygenOutput/html/interface_voxel_busters_1_1_runtime_serialization_1_1_i_runtime_serializable.html) interface.

```
using UnityEngine;
using System.Collections;
using VoxelBusters.RuntimeSerialization;

// Serialization using Attributes
[RuntimeSerializable]
public class Car : IRuntimeSerializable
{
    #region Properties

    public string Model
    {
        get;
        set;
    }

    public int WheelCount
    {
        get;
        set;
    }

    #endregion

    #region Constructors

    public Car ()
    {}

    public Car (string _model, int _wheelCount)
    {
        this.Model        = _model;
        this.WheelCount    = _wheelCount;
    }

    #endregion

    #region IRuntimeSerializable Methods

    // Adding properties to be serialized
    public void WriteSerializationData (RuntimeSerializationInfo _info)
    {
        _info.AddValue&lt;string&gt;("model",     Model);
        _info.AddValue&lt;int&gt;("wheel-count",     WheelCount);
    }

    // Retrieving all serialized properties
    public object ReadSerializationData (RuntimeSerializationInfo _info)
    {
        this.Model        = _info.GetValue&lt;string&gt;("model");
        this.WheelCount    = _info.GetValue&lt;int&gt;("wheel-count");

        return this;
    }

    #endregion
}


public class CarManager 
{
    #region Fields

    private    Car    m_car            = new Car("bmw", 4);
    private    string    m_serializationData    = null;

    #endregion

    #region Methods

    public void Serialize ()
    {
        // Serializing Car instance
        m_serializationData    = RSManager.Serialize&lt;Car&gt;(m_car);
    }

    public void Deserialize ()
    {
        // Deserialization
        m_car                  = RSManager.DeserializeData&lt;Car&gt;(m_serializationData);
    }

    #endregion
}
```

**Trivia: RS supports serialization of Static fields.**
