TweenAlphaSpriteRenderer.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. /// <summary>
  5. /// Tween the object's alpha.
  6. /// </summary>
  7. [RequireComponent(typeof(SpriteRenderer))]
  8. public class TweenAlphaSpriteRenderer : Tweener
  9. {
  10. [Range(0f, 1f)]
  11. public float from = 1f;
  12. [Range(0f, 1f)]
  13. public float to = 1f;
  14. public bool resetOnEnable = false;
  15. SpriteRenderer mGraphic;
  16. /// <summary>
  17. /// Tween's current value.
  18. /// </summary>
  19. public float value {
  20. get {
  21. if (mGraphic == null)
  22. mGraphic = GetComponent<SpriteRenderer>();
  23. return mGraphic.color.a;
  24. }
  25. set {
  26. if (mGraphic == null)
  27. mGraphic = GetComponent<SpriteRenderer>();
  28. Color color = mGraphic.color;
  29. color.a = value;
  30. mGraphic.color = color;
  31. }
  32. }
  33. protected override void Awake()
  34. {
  35. base.Awake();
  36. mGraphic = GetComponent<SpriteRenderer>();
  37. }
  38. void OnEnable()
  39. {
  40. if (resetOnEnable)
  41. {
  42. tweenFactor = 0;
  43. Sample(0, false);
  44. }
  45. }
  46. /// <summary>
  47. /// Tween the value.
  48. /// </summary>
  49. protected override void OnUpdate(float factor, bool isFinished)
  50. {
  51. value = Mathf.Lerp(from, to, factor);
  52. }
  53. /// <summary>
  54. /// Start the tweening operation.
  55. /// </summary>
  56. static public TweenAlphaSpriteRenderer Begin(GameObject go, float duration, float alpha)
  57. {
  58. TweenAlphaSpriteRenderer comp = Tweener.Begin<TweenAlphaSpriteRenderer>(go, duration);
  59. comp.from = comp.value;
  60. comp.to = alpha;
  61. if (duration <= 0f)
  62. {
  63. comp.Sample(1f, true);
  64. comp.enabled = false;
  65. }
  66. return comp;
  67. }
  68. public override void SetStartToCurrentValue()
  69. {
  70. from = value;
  71. }
  72. public override void SetEndToCurrentValue()
  73. {
  74. to = value;
  75. }
  76. }