原文地址 https://blog.youkuaiyun.com/Truck_Truck/article/details/78292390
// Serialization.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
// List<T>
[Serializable]
public class Serialization<T>
{
[SerializeField]
List<T> target;
public List<T> ToList() { return target; }
public Serialization(List<T> target)
{
this.target = target;
}
}
// Dictionary<TKey, TValue>
[Serializable]
public class Serialization<TKey, TValue> : ISerializationCallbackReceiver
{
[SerializeField]
List<TKey> keys;
[SerializeField]
List<TValue> values;
Dictionary<TKey, TValue> target;
public Dictionary<TKey, TValue> ToDictionary() { return target; }
public Serialization(Dictionary<TKey, TValue> target)
{
this.target = target;
}
public void OnBeforeSerialize()
{
keys = new List<TKey>(target.Keys);
values = new List<TValue>(target.Values);
}
public void OnAfterDeserialize()
{
var count = Math.Min(keys.Count, values.Count);
target = new Dictionary<TKey, TValue>(count);
for (var i = 0; i < count; ++i)
{
target.Add(keys[i], values[i]);
}
}
}
在这个思路的基础上封装了两个方法出来更方便使用
public class SerializeTools
{
public static string ListToJson<T>(List<T> l)
{
return JsonUtility.ToJson(new Serialization<T>(l));
}
public static List<T> ListFromJson<T>(string str)
{
return JsonUtility.FromJson<Serialization<T>>(str).ToList();
}
public static string DicToJson<TKey, TValue>(Dictionary<TKey, TValue> dic)
{
return JsonUtility.ToJson(new Serialization<TKey, TValue>(dic));
}
public static Dictionary<TKey, TValue> DicFromJson<TKey, TValue>(string str)
{
return JsonUtility.FromJson<Serialization<TKey, TValue>>(str).ToDictionary();
}
}
本文介绍了一种在Unity中实现自定义泛型序列化的技巧,通过将List和Dictionary类型的数据序列化为JSON字符串来解决Unity中泛型类型的序列化问题。该方法通过自定义的Serialization类实现了List和Dictionary的序列化和反序列化,并提供了工具类简化操作。
7004

被折叠的 条评论
为什么被折叠?



