LowUpdateRate.cs 2.8 KB

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