备忘:
1. ScriptableOjbect中,由于Serialization的原因,不能使用基类引用来存储子类对象,这样都会导致数据丢失
2. 无法直接对Unity的数据如,vector3, quaternion等使用BinaryFormatter进行序列化,会报“SerializationException: Type UnityEngine.Vector3 is not marked as Serializable”。要绕过这个问题的姿势是,自己对Vector3进行包装。下面是其中一种方法
1 using System; 2 using System.Runtime.Serialization; 3 using UnityEngine; 4 5 namespace Assets.Editor 6 { 7 sealed class Vector3SerializationSurrogate : ISerializationSurrogate 8 { 9 10 11 12 public void GetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) 13 { 14 Vector3 v3 = (Vector3)obj; 15 info.AddValue("x", v3.x); 16 info.AddValue("y", v3.y); 17 info.AddValue("z", v3.z); 18 } 19 20 public object SetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISurrogateSelector selector) 21 { 22 Vector3 v3 = (Vector3)obj; 23 v3.x = (float)info.GetValue("x", typeof(float)); 24 v3.y = (float)info.GetValue("y", typeof(float)); 25 v3.z = (float)info.GetValue("z", typeof(float)); 26 27 return (object)v3; 28 } 29 } 30 }
1 public static void TestFunc() 2 { 3 BinaryFormatter bf = new BinaryFormatter(); 4 SurrogateSelector ss = new SurrogateSelector(); 5 6 Vector3SerializationSurrogate v3Surrogate = new Vector3SerializationSurrogate(); 7 ss.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), v3Surrogate); 8 9 bf.SurrogateSelector = ss; 10 11 MemoryStream stream = new MemoryStream(); 12 13 Vector3 testObj = new Vector3(1, 2, 3); 14 bf.Serialize(stream, testObj); 15 stream.Position = 0; 16 Vector3 resultObj = (Vector3)bf.Deserialize(stream); 17 Debug.Log(resultObj); 18 }