AutoSerializer - Trivaxy/Libvaxy GitHub Wiki
AutoSerializer<T>
is a useful type Libvaxy provides in order to make serializing objects into TagCompound
and vice versa extremely easy and automatic. Using AutoSerializers, you almost never have to write saving code, and loading code is simplified. Not only that, but AutoSerializers are very fast at what they do (much faster than reflection-based alternatives other modders may use).
We'll use the following data as an example to AutoSerialize:
public class MyWorld : ModWorld
{
public int CoolInt;
public bool SomethingCoolHappened;
public Vector2 CoolPosition;
public Something CoolThing;
}
AutoSerializers both let you serialize and deserialize data. We'll need to create an instance of AutoSerializer<T>
, where T
is the type we want to serialize. In our case, it's MyWorld
:
AutoSerializer<MyWorld> serializer = new AutoSerializer<MyWorld>();
AutoSerializers have both a Serialize
and Deserialize
method. Serialize
takes an object of the AutoSerializer type you specified, and returns a TagCompound
for you. Deserialize
does the opposite and converts a TagCompound
back to the object whose type you specified.
This can be used in our MyWorld
class to very quickly save and load our data:
public class MyWorld : ModWorld
{
public int CoolInt;
public bool SomethingCoolHappened;
public Vector2 CoolPosition;
public Something CoolThing;
public override TagCompound Save() => new AutoSerializer<MyWorld>().Serialize(this);
public override void Load(TagCompound tag)
{
MyWorld loadedWorld = new AutoSerializer<MyWorld>().Deserialize(tag);
CoolInt = loadedWorld.CoolInt;
SomethingCoolHappened = loadedWorld.SomethingCoolHappened;
CoolPosition = loadedWorld.CoolPosition;
CoolThing = loadedWorld.CoolThing;
}
}
Done! You let AutoSerializers handle a lot of the saving and loading. You can use AutoSerializers anywhere where you need to work with TagCompound
.
Note: AutoSerializer<T>
does not support serializing arrays or collections as of yet. This will be implemented soon and if you want to tackle it, feel free to submit a PR.