ModifySerializedField.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #if UNITY_EDITOR
  3. using System;
  4. using UnityEditor;
  5. using Object = UnityEngine.Object;
  6. namespace Animancer.Editor
  7. {
  8. /// <summary>[Editor-Only]
  9. /// A wrapper for modifying a serialized field to allow it to be properly saved and undone.
  10. /// </summary>
  11. /// <remarks>
  12. /// <strong>Example:</strong>
  13. /// <code>
  14. /// using (new ModifySerializedField(target))// Undo gets captured.
  15. /// {
  16. /// // Modify values on the target.
  17. /// }// Target gets flagged for saving.
  18. /// </code></remarks>
  19. /// https://kybernetik.com.au/animancer/api/Animancer.Editor/ModifySerializedField
  20. public readonly struct ModifySerializedField : IDisposable
  21. {
  22. /************************************************************************************************************************/
  23. /// <summary>The object being modified.</summary>
  24. public readonly Object Target;
  25. /// <summary>Prefab modifications are more complicated to track due to the possibility of nested prefabs.</summary>
  26. public readonly bool MightBePrefab;
  27. /************************************************************************************************************************/
  28. /// <summary>Captures the state of the target as an undo step.</summary>
  29. public ModifySerializedField(
  30. Object target,
  31. string name = "Inspector",
  32. bool mightBePrefab = false)
  33. {
  34. Target = target;
  35. MightBePrefab = mightBePrefab;
  36. if (!string.IsNullOrEmpty(name))
  37. Undo.RecordObject(Target, name);
  38. }
  39. /************************************************************************************************************************/
  40. /// <summary>Flags the target as modified so that it will get saved by Unity.</summary>
  41. public void Dispose()
  42. {
  43. if (MightBePrefab)
  44. PrefabUtility.RecordPrefabInstancePropertyModifications(Target);
  45. EditorUtility.SetDirty(Target);
  46. AnimancerReflection.TryInvoke(Target, "OnValidate");
  47. }
  48. /************************************************************************************************************************/
  49. }
  50. }
  51. #endif