TimeScale.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. using UnityEngine;
  3. namespace Animancer.Samples
  4. {
  5. /// <summary>A simple Inspector slider to control <see cref="Time.timeScale"/>.</summary>
  6. /// <remarks>
  7. /// <strong>Documentation:</strong>
  8. /// <see href="https://kybernetik.com.au/animancer/docs/samples/basics/scene-setup#time-scale">
  9. /// Time Scale</see>
  10. /// </remarks>
  11. /// https://kybernetik.com.au/animancer/api/Animancer.Samples/TimeScale
  12. ///
  13. [AddComponentMenu(Strings.SamplesMenuPrefix + "Time Scale")]
  14. [AnimancerHelpUrl(typeof(TimeScale))]
  15. public class TimeScale : MonoBehaviour
  16. {
  17. /************************************************************************************************************************/
  18. [SerializeField, Range(0, 1)]
  19. private float _Value = 0.5f;
  20. /// <summary>
  21. /// The current <see cref="Time.timeScale"/> or the value that will be assigned when this component is enabled.
  22. /// </summary>
  23. public float Value
  24. {
  25. get => _Value;
  26. set
  27. {
  28. _Value = value;
  29. Time.timeScale = _Value;
  30. }
  31. }
  32. /************************************************************************************************************************/
  33. private float _PreviousValue = 1;
  34. protected virtual void OnEnable()
  35. {
  36. _PreviousValue = Time.timeScale;
  37. Time.timeScale = _Value;
  38. }
  39. protected virtual void OnDisable()
  40. {
  41. Time.timeScale = _PreviousValue;
  42. }
  43. /************************************************************************************************************************/
  44. protected virtual void OnValidate()
  45. {
  46. #if UNITY_EDITOR
  47. if (!UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
  48. return;
  49. #endif
  50. if (enabled)
  51. Time.timeScale = _Value;
  52. }
  53. /************************************************************************************************************************/
  54. }
  55. }