Hey all I am creating my own dictionary class called "Table " which is an abstract class that I plan to inherit into other classes in order to implement property drawers for those. However since unity won’t serialize Dictionary, is it okay to build my class like this for serialization purposes? Or is there a better way to handle this?
(This Class is not quite complete yet but you get the idea :))
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public abstract class Table <TKey, TValue> {
public byte[] bytes = new byte[0];
Dictionary<TKey,TValue> dict = new Dictionary<TKey, TValue> ();
public Dictionary<TKey,TValue> dictionary{
get{
if(dict.Count == 0 && bytes.LongLength > 0){
Deserialize ();
}
return dict;
}
set{
dict = value;
Serialize ();
}
}
public void Add(TKey key, TValue value){
if (!ContainsKey (key)) {
dictionary.Add (key, value);
Serialize ();
return;
}
throw(new System.Exception ("The Table Already Contains The Key \"" + key.ToString () + "\"."));
}
public TValue this[TKey key]{
get{
if(ContainsKey (key)){
return dictionary[key];
}
throw (new System.Exception("The Key : \"" + key.ToString () + "\" Does Not Exist."));
}
set{
if(ContainsKey (key)){
dictionary[key] = value;
}
else{
Add (key, value);
}
Serialize ();
}
}
public bool ContainsKey(TKey key){
return dictionary.ContainsKey (key);
}
void Serialize(){
BinaryFormatter formatter = new BinaryFormatter ();
MemoryStream stream = null;
try{
stream = new MemoryStream();
formatter.Serialize (stream, dict);
bytes = stream.ToArray ();
}
catch{
bytes = new byte[0];
}
finally{
if(stream != null)stream.Close ();
}
}
void Deserialize(){
BinaryFormatter formatter = new BinaryFormatter ();
MemoryStream stream = null;
try{
stream = new MemoryStream(bytes);
dict = (Dictionary<TKey, TValue>) formatter.Deserialize (stream);
}
catch{
return;
}
finally{
if(stream != null) stream.Close ();
}
}
}
Thanks In Advance!