TweenAlphaRenderer.cs 1.9 KB

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