嗚嗚喔學習筆記: Unity Serialization by Json or Binary

搜尋此網誌

2020年4月24日 星期五

Unity Serialization by Json or Binary

對於Unity 序列化 & 反序列化 大致上有的選擇有 Json , Binary , YAML
YAML屬於Unity Prefab 儲存格式沒啥問題先不討論。


Json 我選用 LitJSON
Binary 選用 BinaryFormatter

總之因為這兩個都沒對 Unity 的特定資料結構處理 比如Vector2 Vector3 之類的所以使用上會出現下面的問題


Json 出現的問題 : 


JsonException: Max allowed object depth reached while trying to export from type UnityEngine.Vector2

Binary 出現問題 : 


UnityEngine.Vector2' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

經過Google一番,總之就是新增定義Unity專用的序列方法,總之我把他解決了並且放在GitHub上。
連結在這 :


使用範例 : 


using EasyButtons; using LitJson; using System; using System.IO; using UnityEngine; [Serializable] public class Test { public Vector3 Vec3 = new Vector3(1f, 2f, 3f); public Vector2 Vec2 = new Vector2(4f, 5f); } public class Example : MonoBehaviour { [Button] public void DataToJson() { string path = Path.Combine(Application.dataPath, "Test.json"); string json = JsonMapper.ToPrettyJson(new Test()); File.WriteAllText(path, json); } [Button] public void JsonToData() { string path = Path.Combine(Application.dataPath, "Test.json"); string json = File.ReadAllText(path); Test test = JsonMapper.ToObject<Test>(json); Debug.LogFormat("vec2{0} vec3 {1}", test.Vec2, test.Vec3); } [Button] public void DataToBytes() { string path = Path.Combine(Application.dataPath, "Test.bytes"); byte[] b = BytesMapper.ToBytes<Test>(new Test()); File.WriteAllBytes(path, b); } [Button] public void BytesToData() { string path = Path.Combine(Application.dataPath, "Test.bytes"); byte[] b = File.ReadAllBytes(path); Test test = BytesMapper.ToObject<Test>(b); Debug.LogFormat("vec2{0} vec3 {1}", test.Vec2, test.Vec3); } }

沒有留言:

張貼留言