CustomRecorder.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using Chronos.Reflection;
  4. using UnityEngine;
  5. namespace Chronos
  6. {
  7. public class CustomRecorder : Recorder<CustomRecorder.Snapshot>
  8. {
  9. public class Snapshot
  10. {
  11. public object[] values { get; private set; }
  12. public Snapshot(int size)
  13. {
  14. values = new object[size];
  15. }
  16. }
  17. [SerializeField, SelfTargeted, Filter(TypeFamilies = TypeFamily.Value, Inherited = true, ReadOnly = false)]
  18. private List<UnityVariable> variables;
  19. public CustomRecorder()
  20. {
  21. variables = new List<UnityVariable>();
  22. }
  23. protected override void ApplySnapshot(Snapshot snapshot)
  24. {
  25. int i = 0;
  26. foreach (UnityVariable variable in variables)
  27. {
  28. variable.Set(snapshot.values[i++]);
  29. }
  30. }
  31. protected override Snapshot CopySnapshot()
  32. {
  33. Snapshot snapshot = new Snapshot(variables.Count);
  34. int i = 0;
  35. foreach (UnityVariable variable in variables)
  36. {
  37. snapshot.values[i++] = variable.Get();
  38. }
  39. return snapshot;
  40. }
  41. protected override Snapshot LerpSnapshots(Snapshot from, Snapshot to, float t)
  42. {
  43. Snapshot snapshot = new Snapshot(from.values.Length);
  44. for (int i = 0; i < snapshot.values.Length; i++)
  45. {
  46. snapshot.values[i] = LerpValue(from.values[i], to.values[i], t);
  47. }
  48. return snapshot;
  49. }
  50. private static object LerpValue(object from, object to, float t)
  51. {
  52. object inter;
  53. Type type = from.GetType();
  54. if (type == typeof(float) || type == typeof(double)) inter = Mathf.Lerp((float)from, (float)to, t);
  55. else if (type == typeof(Vector3)) inter = Vector3.Lerp((Vector3)from, (Vector3)to, t);
  56. else if (type == typeof(Vector2)) inter = Vector2.Lerp((Vector2)from, (Vector2)to, t);
  57. else if (type == typeof(Quaternion)) inter = Quaternion.Lerp((Quaternion)from, (Quaternion)to, t);
  58. else if (type == typeof(Color)) inter = Color.Lerp((Color)from, (Color)to, t);
  59. else inter = from;
  60. return inter;
  61. }
  62. }
  63. }