- Home /
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?
You should note that the "Serializable types" mentioned in the docs refer to types that can be serialized in the inspector. $$anonymous$$any Unity types (such as the Vector3) cannot be serialized by a BinaryFormatter.
Yes, I was specifically referring to serializing to the Inspector.
Answer by CJCurrie · Apr 05, 2011 at 06:35 PM
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.
See my answer at http://answers.unity3d.com/questions/971/how-to-scrip-a-save-load-game-option/50717#50717 for more information on a complete implementation.