Can you serialize a hash table?

From the docs:

Serializable types are:

  • All classed inheriting from UnityEngine.Object, for example Gameobject, Commponent, 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 (new in Unity2.6)
  • Enums

By list of a serializable type, do they mean hashes can be serialized?

Yes, hashtables can be serialized (edit: in both a BinaryFormatter and the inspector). If you look at the MSDN you'll see

` [SerializableAttribute] [ComVisibleAttribute(true)] public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable `

The [SerializableAttribute] tag means it's definitely serializable by a BinaryFormatter. Furthermore, the following code is tested to work. You should recognize it from ISerializable implementations:


  public SaveData (SerializationInfo info, StreamingContext ctxt)
  {
    currentLevel = (uint)info.GetValue("currentLevel", typeof(uint));

    // === Events ===
    events = (Hashtable)info.GetValue("events", typeof(Hashtable));
  }

  public void GetObjectData (SerializationInfo info, StreamingContext ctxt)
  {
    info.AddValue("currentLevel", currentLevel);

    // === Events === 
    info.AddValue("events", events);
  }

I personally found it very useful to keep track of which scripted events have been triggered by the player, as putting all those into a List would suck to have to remember.

Note that XML serialization is a different beast and doesn't play with Hashtables.