Recorder.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using UnityEngine;
  2. namespace Chronos
  3. {
  4. /// <summary>
  5. /// An abstract base component that saves snapshots at regular intervals to enable rewinding.
  6. /// </summary>
  7. [HelpURL("http://ludiq.io/chronos/documentation#Recorder")]
  8. public abstract class Recorder<TSnapshot> : MonoBehaviour
  9. {
  10. private bool enabledOnce;
  11. private class DelegatedRecorder : RecorderTimeline<Component, TSnapshot>
  12. {
  13. private Recorder<TSnapshot> parent;
  14. public DelegatedRecorder(Recorder<TSnapshot> parent, Timeline timeline) : base(timeline, null)
  15. {
  16. this.parent = parent;
  17. }
  18. protected override void ApplySnapshot(TSnapshot snapshot)
  19. {
  20. parent.ApplySnapshot(snapshot);
  21. }
  22. protected override TSnapshot CopySnapshot()
  23. {
  24. return parent.CopySnapshot();
  25. }
  26. protected override TSnapshot LerpSnapshots(TSnapshot from, TSnapshot to, float t)
  27. {
  28. return parent.LerpSnapshots(from, to, t);
  29. }
  30. }
  31. protected virtual void Awake()
  32. {
  33. CacheComponents();
  34. }
  35. protected virtual void Start()
  36. {
  37. recorder.OnStartOrReEnable();
  38. }
  39. protected virtual void OnEnable()
  40. {
  41. if (enabledOnce)
  42. {
  43. recorder.OnStartOrReEnable();
  44. }
  45. else
  46. {
  47. enabledOnce = true;
  48. }
  49. }
  50. protected virtual void Update()
  51. {
  52. recorder.Update();
  53. }
  54. protected virtual void OnDisable()
  55. {
  56. recorder.OnDisable();
  57. }
  58. /// <summary>
  59. /// Modifies all snapshots via the specified modifier delegate.
  60. /// </summary>
  61. public virtual void ModifySnapshots(RecorderTimeline<Component, TSnapshot>.SnapshotModifier modifier)
  62. {
  63. recorder.ModifySnapshots(modifier);
  64. }
  65. private Timeline timeline;
  66. private RecorderTimeline<Component, TSnapshot> recorder;
  67. protected abstract void ApplySnapshot(TSnapshot snapshot);
  68. protected abstract TSnapshot CopySnapshot();
  69. protected abstract TSnapshot LerpSnapshots(TSnapshot from, TSnapshot to, float t);
  70. public virtual void CacheComponents()
  71. {
  72. timeline = GetComponentInParent<Timeline>();
  73. if (timeline == null)
  74. {
  75. throw new ChronosException(string.Format("Missing timeline for recorder."));
  76. }
  77. recorder = new DelegatedRecorder(this, timeline);
  78. }
  79. }
  80. }