VersionedMonoBehaviour.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using UnityEngine;
  2. namespace Pathfinding {
  3. /// <summary>Exposes internal methods from <see cref="Pathfinding.VersionedMonoBehaviour"/></summary>
  4. public interface IVersionedMonoBehaviourInternal {
  5. void UpgradeFromUnityThread ();
  6. }
  7. /// <summary>Base class for all components in the package</summary>
  8. public abstract class VersionedMonoBehaviour : MonoBehaviour, ISerializationCallbackReceiver, IVersionedMonoBehaviourInternal {
  9. /// <summary>Version of the serialized data. Used for script upgrades.</summary>
  10. [SerializeField]
  11. [HideInInspector]
  12. int version = 0;
  13. protected virtual void Awake () {
  14. // Make sure the version field is up to date for components created during runtime.
  15. // Reset is not called when in play mode.
  16. // If the data had to be upgraded then OnAfterDeserialize would have been called earlier.
  17. if (Application.isPlaying) version = OnUpgradeSerializedData(int.MaxValue, true);
  18. }
  19. /// <summary>Handle serialization backwards compatibility</summary>
  20. protected virtual void Reset () {
  21. // Set initial version when adding the component for the first time
  22. version = OnUpgradeSerializedData(int.MaxValue, true);
  23. }
  24. /// <summary>Handle serialization backwards compatibility</summary>
  25. void ISerializationCallbackReceiver.OnBeforeSerialize () {
  26. }
  27. /// <summary>Handle serialization backwards compatibility</summary>
  28. void ISerializationCallbackReceiver.OnAfterDeserialize () {
  29. var r = OnUpgradeSerializedData(version, false);
  30. // Negative values (-1) indicate that the version number should not be updated
  31. if (r >= 0) version = r;
  32. }
  33. /// <summary>Handle serialization backwards compatibility</summary>
  34. protected virtual int OnUpgradeSerializedData (int version, bool unityThread) {
  35. return 1;
  36. }
  37. void IVersionedMonoBehaviourInternal.UpgradeFromUnityThread () {
  38. var r = OnUpgradeSerializedData(version, true);
  39. if (r < 0) throw new System.Exception();
  40. version = r;
  41. }
  42. }
  43. }