From 19d968d8c0d7b71858ff84711a5181d701b54498 Mon Sep 17 00:00:00 2001 From: Mikhail <99481254+DCFApixels@users.noreply.github.com> Date: Mon, 16 Sep 2024 19:31:55 +0800 Subject: [PATCH] add recovery reference --- src/Utils/Reference.cs | 61 +++++++++++++++++++++++++++++++++++++ src/Utils/Reference.cs.meta | 11 +++++++ 2 files changed, 72 insertions(+) create mode 100644 src/Utils/Reference.cs create mode 100644 src/Utils/Reference.cs.meta diff --git a/src/Utils/Reference.cs b/src/Utils/Reference.cs new file mode 100644 index 0000000..b2f42ad --- /dev/null +++ b/src/Utils/Reference.cs @@ -0,0 +1,61 @@ +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace DCFApixels.DragonECS +{ + [System.Serializable] + public struct Reference +#if UNITY_EDITOR + : ISerializationCallbackReceiver +#endif + { +#if UNITY_EDITOR + [SerializeReference] + private T _value; + [SerializeField] + private string _json; + public T Value + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return _value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set { _value = value; } + } +#else + public T Value; +#endif + +#if UNITY_EDITOR + private static System.Collections.Generic.Dictionary _metaIDTypePairs; + private static void InitRecoverCache() + { + if (_metaIDTypePairs == null) { return; } + _metaIDTypePairs = new System.Collections.Generic.Dictionary(); + } + private static T TryRecoverReference(string metaID) + { + InitRecoverCache(); + if (_metaIDTypePairs.TryGetValue(metaID, out System.Type type)) + { + return (T)System.Activator.CreateInstance(type); + } + return default; + } + void ISerializationCallbackReceiver.OnAfterDeserialize() + { + if (_value == null) + { + int indexof = _json.IndexOf(','); + _value = TryRecoverReference(_json.Substring(0, indexof)); + if (_value == null) { return; } + JsonUtility.FromJsonOverwrite(_json.Substring(indexof + 1), _value); + _json = null; + } + } + void ISerializationCallbackReceiver.OnBeforeSerialize() + { + _json = $"{_value.GetMeta().MetaID},{JsonUtility.ToJson(_value)}"; + } +#endif + } +} diff --git a/src/Utils/Reference.cs.meta b/src/Utils/Reference.cs.meta new file mode 100644 index 0000000..783b168 --- /dev/null +++ b/src/Utils/Reference.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6399ac2dd5218444b98f4dcf3a359611 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: