Skip to content

Instantly share code, notes, and snippets.

@g0ody
Last active December 15, 2015 17:50
Show Gist options
  • Save g0ody/5299674 to your computer and use it in GitHub Desktop.
Save g0ody/5299674 to your computer and use it in GitHub Desktop.
Serializer Class for Unity3D to Convert MonoBehaviour Objects in Hashtables, which can be parsed to JSON or XML *Serializes only the first MonoBehaviour of each GameObject, and loops through Children*
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System;
public class SerializeUtility
{
public static ArrayList ArrayToArrayList<T, U>(T[] data, Converter<T, U> converter)
{
return ArrayList.Adapter(Array.ConvertAll(data, converter));
}
public static U[] ArrayListToArray<T, U>(ArrayList data, Converter<T, U> converter)
{
if (data != null)
return Array.ConvertAll((T[])data.ToArray(typeof(T)), converter);
else
return new U[0];
}
public static Hashtable DictonaryToHashtable<T, U>(Dictionary<string, T> data, Converter<T, U> converter)
{
Hashtable result = new Hashtable();
foreach (var key in data.Keys)
result[key] = converter(data[key]);
return result;
}
public static Dictionary<string, U> HashtableToDictonary<T, U>(Hashtable data, Converter<T, U> converter)
{
Dictionary<string, U> result = new Dictionary<string, U>();
foreach (var key in data.Keys)
result[Convert.ToString(key)] = converter((T)data[key]);
return result;
}
public static Hashtable Serialize( object obj)
{
Hashtable result = new Hashtable();
if (obj != null)
{
foreach (FieldInfo field in obj.GetType().GetFields())
if (field.IsPublic && !field.FieldType.IsClass)
if(field.FieldType.IsEnum)
result[field.Name] = Convert.ToInt32(field.GetValue(obj));
else
result[field.Name] = field.GetValue(obj);
}
return result;
}
public static Hashtable Serialize(Transform parent)
{
Hashtable result = SerializeUtility.Serialize(parent.GetComponent<MonoBehaviour>());
var count = parent.GetChildCount();
for (var i = 0; i < count; i++)
{
var child = parent.GetChild(i);
result[child.name] = SerializeUtility.Serialize(child);
}
return result;
}
public static void Deserialize(object obj, Hashtable data)
{
if (obj != null && data != null)
{
foreach (FieldInfo field in obj.GetType().GetFields())
if (field.IsPublic && !field.FieldType.IsClass && data.ContainsKey(field.Name))
if (field.FieldType.IsEnum)
field.SetValue(obj, Convert.ToInt32(data[field.Name]));
else
field.SetValue(obj, Convert.ChangeType(data[field.Name], field.FieldType));
}
}
public static void Deserialize(Transform parent, Hashtable data)
{
if (data != null)
{
SerializeUtility.Deserialize(parent.GetComponent<MonoBehaviour>(), data);
var count = parent.GetChildCount();
for (var i = 0; i < count; i++)
{
var child = parent.GetChild(i);
if( data.ContainsKey(child.name))
SerializeUtility.Deserialize(child, data[child.name] as Hashtable);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment