Tricks of Serialization in Unity/C#

来源:互联网 发布:als矩阵分析 编辑:程序博客网 时间:2024/05/17 08:34

Tricks of Serialization in Unity/C#


Don’t use XmlSerializer

  • XmlSerializer + StringWriter is sloooooow
  • XmlSerializer does NOT require [Serializable]
  • XmlSerializer does NOT support ISerializable

Use BinaryFormatter + MemoryStream. It’s fast and customizable.

Use System.Diagnostics.Stopwatch for simple profile.

Use Encoding.ASCII.GetString() to convert MemorySteam to string
Use Convert.ToBase64String for binary data that contains ‘\0’

IFormatter formatter = new BinaryFormatter();MemoryStream stream = new MemoryStream();formatter.Serialize(stream, target);string result = Convert.ToBase64String(stream.ToArray());//string result = Encoding.ASCII.GetString(stream.ToArray());

Another “trick” for BinaryFormatter in Unity/iOS :
http://answers.unity3d.com/questions/30930/why-did-my-binaryserialzer-stop-working.html

// Just add the following line to the Awake() function of the MonoBehaviour// script and the BinaryFormatter should work fine on iOS. // Forces a different code path in the BinaryFormatter that doesn't rely on // run-time code generation (which would break on iOS).Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes")
0 0