UiAnimator.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. namespace KairoEngine.UI
  6. {
  7. public class UiAnimator : MonoBehaviour
  8. {
  9. public GameObject objectToAnimate;
  10. public float delay = 0f;
  11. public float disableDelay = 0f;
  12. public bool animateOnEnable;
  13. public bool animateOnDisable;
  14. public bool disableObjectOnEnd = true;
  15. public bool animateScale = true;
  16. [ShowIf(@"animateScale")] public float scaleDuration = 0.3f;
  17. [ShowIf(@"animateScale")] public Vector3 sacelFrom;
  18. [ShowIf(@"animateScale")] public Vector3 scaleTo;
  19. public bool animateAlpha = true;
  20. [ShowIf(@"animateAlpha")] public float alphaDuration = 0.1f;
  21. [ShowIf(@"animateAlpha")] public float alphaFrom = 0f;
  22. [ShowIf(@"animateAlpha")] public float alphaTo = 1f;
  23. private LTDescr _tweenObject = new LTDescr();
  24. public void OnEnable()
  25. {
  26. if(animateOnEnable)
  27. {
  28. Animate();
  29. }
  30. }
  31. public void Disable()
  32. {
  33. if(animateOnDisable == false)
  34. {
  35. if(disableObjectOnEnd) gameObject.SetActive(false);
  36. return;
  37. }
  38. SwapDirection();
  39. Animate();
  40. _tweenObject.setDelay(disableDelay).setOnComplete(() => {
  41. SwapDirection();
  42. if(disableObjectOnEnd) gameObject.SetActive(false);
  43. });
  44. }
  45. private void Animate()
  46. {
  47. //Debug.Log("Animating UI");
  48. if(_tweenObject == null) {
  49. _tweenObject = new LTDescr();
  50. }
  51. if(objectToAnimate == null)
  52. {
  53. objectToAnimate = gameObject;
  54. }
  55. // Scale Animation
  56. if(animateScale)
  57. {
  58. objectToAnimate.GetComponent<RectTransform>().localScale = sacelFrom;
  59. _tweenObject = LeanTween.scale(objectToAnimate, scaleTo, scaleDuration).setIgnoreTimeScale( true ).setDelay(delay);
  60. }
  61. // Fade Animaion
  62. if(animateAlpha)
  63. {
  64. CanvasGroup canvas = objectToAnimate.GetComponent<CanvasGroup>();
  65. if(canvas == null)
  66. {
  67. objectToAnimate.AddComponent<CanvasGroup>();
  68. canvas = objectToAnimate.GetComponent<CanvasGroup>();
  69. }
  70. canvas.alpha = alphaFrom;
  71. _tweenObject = LeanTween.alphaCanvas(canvas, alphaTo, alphaDuration).setIgnoreTimeScale( true ).setDelay(delay);
  72. }
  73. }
  74. private void SwapDirection()
  75. {
  76. var scaleTemp = sacelFrom;
  77. sacelFrom = scaleTo;
  78. scaleTo = scaleTemp;
  79. var alphaTemp = alphaFrom;
  80. alphaFrom = alphaTo;
  81. alphaTo = alphaTemp;
  82. }
  83. }
  84. }