Sunday, April 12, 2015

Unity3d Hybird Serialization UnityVariable


Serialization/Deserialization is hidden Diablo inside Unity. 
You can fight it( remember you are on their ground!!!) and create your own custom system based on Protobuf, JSON (I dislike it)... or some other, or you can bend the knee. I choose to make hybrid. 
I left Unity to take care of everything that subclass UnityObject + UnityEvent and create custom serialization for the rest thru C# built in BinaryFormatter. BinaryFormatter know how to serialize .NET types, but for Unity primitive types( Vector3, Rect, AnimationCurve,...) you need to create Surrogates. Which is more boring then some complex task.



Part of custom serialized data should be saved somewhere, so can be deserialized. Some solutions are using binary files (ex .dat,.bin) which is ok. But I disapprove solutions that put binary data, previous convert into Base64, into PlayerPref as string. As I found out that Unity know how to serialize ByteArray, I implemented new ISerializationCallbackReceiver and return the ball back to Unity letting Unity ser/des ByteArray of custom serialized data.





Where to use it?
You can create Blackboard with list of variables that can be add/change/removed without code having visual programming in hand.



You can create your variable inside your inspectors/editors:

[UnityVariablePropertyAttribute(typeof(float))]
    public UnityVariable variable6;


[UnityVariablePropertyAttribute(typeof(AnimationClip))]
    public UnityVariable variable7;


Then you can use Raw value ex. 5.6f or Bind to some other GameObject/Component float property or reference variable from Blackboard making your tools more flexible.



Source: GITHUB

No comments:

Post a Comment