欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 序列化的问题

程序员文章站 2022-04-03 12:37:00
...

Unity 序列化

  • 当我用父类引用子类的实例时,序列化只会保存父类的数据。
  • 解决这种问题只能使用Json序列化
  • 继承unity的序列化接口,用一个字符串保存真正的值,在序列化之前和序列化之后,对这个字符串进行还原。代码如下
[Serializable]
	public class VFXStageSetting : ISerializationCallbackReceiver
	{

		public string effectType;
		public VFXAction action;
		public bool edit;

		[SerializeField]
		public string dataStr;
		IReadOnlyDictionary<string, Type> types = (from assembly in AppDomain.CurrentDomain.GetAssemblies ()
												   from type in assembly.GetTypes ()
												   where type.IsSubclassOf (typeof (VFXAction))
												   let attribute = type.GetCustomAttribute<EffectActionAttribute> (false)
												   select (attribute.showName, type)).ToReadOnlyDictionary (p => p.showName, p => p.Item2);

		void ISerializationCallbackReceiver.OnAfterDeserialize ()
		{
			action = (VFXAction)JsonConvert.DeserializeObject (dataStr, types[effectType]);
		}

		void ISerializationCallbackReceiver.OnBeforeSerialize ()
		{
			dataStr = JsonConvert.SerializeObject (action);
		}
	}
相关标签: Unity