Skip to content

Instantly share code, notes, and snippets.

@jagt
Created July 28, 2015 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagt/cb64ba74a520b4929b30 to your computer and use it in GitHub Desktop.
Save jagt/cb64ba74a520b4929b30 to your computer and use it in GitHub Desktop.
Full serializer custom converter.
using System;
using System.Collections.Generic;
using FullInspector;
using FullSerializer;
using UnityEngine;
public class Foo
{
public MagicFloat bar;
public MagicFloat boot;
}
[fsObject(Converter = typeof(ConfigMagicFloatConverter))]
public class MagicFloat
{
public bool isCalculated;
public float value;
public string key;
}
public class ConfigMagicFloatConverter : fsConverter
{
public override object CreateInstance(fsData data, Type storageType)
{
return new MagicFloat();
}
public override bool CanProcess(Type type)
{
return type == typeof(MagicFloat);
}
public override bool RequestInheritanceSupport(Type storageType)
{
return false;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
{
MagicFloat mf = instance as MagicFloat;
if (mf == null)
{
serialized = new fsData();
return fsResult.Fail("Failed to convert MagicFloat");
}
serialized = mf.isCalculated ? new fsData(mf.key) : new fsData(mf.value);
return fsResult.Success;
}
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType)
{
MagicFloat magicFloat = (MagicFloat)instance;
if (data.IsDouble)
{
magicFloat.isCalculated = false;
magicFloat.value = (float)data.AsDouble;
return fsResult.Success;
}
else if (data.IsString)
{
magicFloat.isCalculated = true;
magicFloat.key = data.AsString;
return fsResult.Success;
}
return fsResult.Fail("MagicFloat field needs to be either float or string.");
}
}
public class MonoTestLoadOut : MonoBehaviour
{
public void Awake()
{
string str = Resources.Load<TextAsset>("Foo").text;
var foo = SerializationHelpers.DeserializeFromContent<Foo, FullSerializerSerializer>(str);
Debug.Log(foo.bar.key);
Debug.Log(foo.bar.value);
Debug.Log(foo.bar.isCalculated);
/////////////////////////////////////
Debug.Log(foo.boot.key);
Debug.Log(foo.boot.value);
Debug.Log(foo.boot.isCalculated);
Debug.Log(foo.bar == foo.boot);
Debug.Log(SerializationHelpers.SerializeToContent<Foo, FullSerializerSerializer>(foo));
var altFoo = new Foo();
altFoo.boot = new MagicFloat();
altFoo.boot.key = "what?";
Debug.Log(SerializationHelpers.SerializeToContent<Foo, FullSerializerSerializer>(altFoo));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment