DynamicUpdateRate.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 Animancer.Units;
  4. using UnityEngine;
  5. namespace Animancer.Examples.FineControl
  6. {
  7. /// <summary>
  8. /// Demonstrates how to save some performance by updating Animancer at a lower frequency when the character is far
  9. /// away from the camera.
  10. /// </summary>
  11. /// <example><see href="https://kybernetik.com.au/animancer/docs/examples/fine-control/update-rate">Update Rate</see></example>
  12. /// https://kybernetik.com.au/animancer/api/Animancer.Examples.FineControl/DynamicUpdateRate
  13. ///
  14. [AddComponentMenu(Strings.ExamplesMenuPrefix + "Fine Control - Dynamic Update Rate")]
  15. [HelpURL(Strings.DocsURLs.ExampleAPIDocumentation + nameof(FineControl) + "/" + nameof(DynamicUpdateRate))]
  16. public sealed class DynamicUpdateRate : MonoBehaviour
  17. {
  18. /************************************************************************************************************************/
  19. [SerializeField] private LowUpdateRate _LowUpdateRate;
  20. [SerializeField] private TextMesh _TextMesh;
  21. [SerializeField, Meters] private float _SlowUpdateDistance = 5;
  22. private Transform _Camera;
  23. /************************************************************************************************************************/
  24. private void Awake()
  25. {
  26. // Finding the Camera.main is a slow operation so we don't want to repeat it every update.
  27. _Camera = Camera.main.transform;
  28. }
  29. /************************************************************************************************************************/
  30. private void Update()
  31. {
  32. // Compare the squared distance to the camera with the squared threshold.
  33. // This is more efficient than calculating the distance because it avoids the square root calculation.
  34. var offset = _Camera.position - transform.position;
  35. var squaredDistance = offset.sqrMagnitude;
  36. // enabled = true if the distance is larger.
  37. // enabled = false if the distance is smaller
  38. _LowUpdateRate.enabled = squaredDistance > _SlowUpdateDistance * _SlowUpdateDistance;
  39. // For the sake of this example, use a TextMesh to show the current details.
  40. var distance = Mathf.Sqrt(squaredDistance);
  41. var updating = _LowUpdateRate.enabled ? "Slowly" : "Normally";
  42. _TextMesh.text = $"Distance {distance}\nUpdating {updating}\n\nDynamic Rate";
  43. }
  44. /************************************************************************************************************************/
  45. }
  46. }