using System; using System.Collections.Generic; using System.Reflection; using UnityEngine; public class Tools { /// /// 深拷贝 通过反射 /// /// 拷贝类型 /// 拷贝对象 /// 复制体 public static T DeepCopyByReflect(T obj) { //如果是字符串或值类型则直接返回 if (obj == null || (obj is string) || (obj.GetType().IsValueType)) return obj; object retval = Activator.CreateInstance(obj.GetType()); FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo field in fields) { try { field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj))); } catch { } } return (T)retval; } } // 序列化 List [Serializable] public class Serialization { [SerializeField] List target; public List ToList() { return target; } public Serialization(List target) { this.target = target; } } // 序列化 Dictionary [Serializable] public class Serialization : ISerializationCallbackReceiver { [SerializeField] List keys; [SerializeField] List values; Dictionary target; public Dictionary ToDictionary() { return target; } public Serialization(Dictionary target) { this.target = target; } public void OnBeforeSerialize() { keys = new List(target.Keys); values = new List(target.Values); } public void OnAfterDeserialize() { var count = Math.Min(keys.Count, values.Count); target = new Dictionary(count); for (var i = 0; i < count; ++i) { target.Add(keys[i], values[i]); } } }