LowUpdateRate.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value.
  3. using Animancer.Units;
  4. using UnityEngine;
  5. namespace Animancer.Samples.FineControl
  6. {
  7. /// <summary>Demonstrates how to save some performance by updating Animancer less often.</summary>
  8. ///
  9. /// <remarks>
  10. /// <strong>Sample:</strong>
  11. /// <see href="https://kybernetik.com.au/animancer/docs/samples/fine-control/update-rate">
  12. /// Update Rate</see>
  13. /// </remarks>
  14. ///
  15. /// https://kybernetik.com.au/animancer/api/Animancer.Samples.FineControl/LowUpdateRate
  16. ///
  17. [AddComponentMenu(Strings.SamplesMenuPrefix + "Fine Control - Low Update Rate")]
  18. [AnimancerHelpUrl(typeof(LowUpdateRate))]
  19. public class LowUpdateRate : MonoBehaviour
  20. {
  21. /************************************************************************************************************************/
  22. // This script doesn't play any animations.
  23. // In a real game, you would have other scripts doing that.
  24. // But for this sample, we're just using a NamedAnimancerComponent for its Play Automatically field.
  25. [SerializeField] private AnimancerComponent _Animancer;
  26. [SerializeField, PerSecond] private float _UpdatesPerSecond = 5;
  27. private float _LastUpdateTime;
  28. /************************************************************************************************************************/
  29. // The DynamicUpdateRate script will enable and disable this script.
  30. /************************************************************************************************************************/
  31. protected virtual void OnEnable()
  32. {
  33. _Animancer.Graph.PauseGraph();
  34. _LastUpdateTime = Time.time;
  35. }
  36. protected virtual void OnDisable()
  37. {
  38. // This will get called when destroying the object as well (such as when loading a different scene).
  39. // So we need to make sure the AnimancerComponent still exists and is still initialized.
  40. if (_Animancer != null && _Animancer.IsGraphInitialized)
  41. _Animancer.Graph.UnpauseGraph();
  42. }
  43. /************************************************************************************************************************/
  44. protected virtual void Update()
  45. {
  46. float time = Time.time;
  47. float timeSinceLastUpdate = time - _LastUpdateTime;
  48. if (timeSinceLastUpdate > 1 / _UpdatesPerSecond)
  49. {
  50. _Animancer.Evaluate(timeSinceLastUpdate);
  51. _LastUpdateTime = time;
  52. }
  53. }
  54. /************************************************************************************************************************/
  55. }
  56. }